属性 'then' 在 Observable 类型上不存在

Property 'then' does not exist on type Observable

我是 angular 2 的新手,我正在尝试发出 REST GET 请求,但在尝试时遇到此错误:

error TS2339: Property 'then' does not exist on type 'Observable<Connection[]>'.

调用服务的组件如下:

import { Component, OnInit} from '@angular/core';
import { Router }           from '@angular/router';

import { Connection }       from './connection';
import { ConnectionService }      from './connection.service';

let $: any = require('../scripts/jquery-2.2.3.min.js');

@Component({
  selector: 'connections',
  styleUrls: [ 'connections.component.css' ],
  templateUrl: 'connections.component.html',
  providers: [ConnectionService]
})

export class ConnectionsComponent implements OnInit {

  connections: Connection[];
  selectedConnection: Connection;

  constructor(
    private connectionService: ConnectionService,
    private router: Router) { }

  getConnections(): void {
    this.connectionService.getConnections().then(connections => {
      this.connections = connections;
    });
  }

  ngOnInit(): void {
    this.getConnections();
  }

  onSelect(connection: Connection): void {
    this.selectedConnection = connection;
  }

  gotoDetail(): void {
    this.router.navigate(['/connectiondetail', this.selectedConnection.id]);
  }
}

这是连接服务:

import { Injectable }     from '@angular/core';
import { Http, Response } from '@angular/http';
import { Connection }     from './connection';
import { Observable }     from 'rxjs/Observable';

@Injectable()
export class ConnectionService {

  private connectionsUrl = 'https://localhost/api/connections';  // URL to web API

  constructor (private http: Http) {}

  getConnections(): Observable<Connection[]> {
    return this.http.get(this.connectionsUrl)
                    .map(this.extractData)
                    .catch(this.handleError);
  }

  private extractData(res: Response) {
    let body = res.json();
    return body.data || { };
  }

  private handleError (error: Response | any) {
    // In a real world app, we might use a remote logging infrastructure

    let errMsg: string;

    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }

    console.error(errMsg);

    return Observable.throw(errMsg);
  }
}

如何修复此错误?

谢谢,

汤姆

Observable 不像 then 那样有类似 promise 的方法。在您的服务中,您正在执行一个 http 调用,其中 returns 一个 Observable,并且您将这个 Observable 映射到另一个 Observable。

如果你真的想使用 promise 风格 API,你需要使用 toPromise 运算符将 Observable 转换为 promise。该运算符默认不可用,因此您还需要在项目中导入一次。

import 'rxjs/add/operator/toPromise';

使用 promises 没问题,但有一些很好的理由直接使用 Observable APIs。有关详细信息,请参阅此 blog post 广告 Observables 的用法。

如果您想直接使用 Observable API,请将您的 then 调用替换为 subscribe 调用。但请记住,当您的组件被销毁时,每个订阅也需要取消。

getConnections(): void {
  this.subscription = this.connectionService.getConnections()
    .subscribe(connections => this.connections = connections);
}

ngOnDestroy() {
  this.subscription.unsubscribe();
}

使用 Observable 时的另一个选择是将生成的 Observable 分配给组件中的一个字段,然后使用 async pipe。这样做,Angular 将为您处理订阅。

在两者之间添加 .toPromise() 使其成为一个承诺

对于Angular我是通过下面的方式解决的,我只需要添加.toPromise方法来转换观察者。

GetUsersData() {
    const UsuariosCollection = this.afs.collection('usuarios').get();

    UsuariosCollection.toPromise().then((snapshot) => {
      snapshot.forEach((doc) => {
        console.log(doc.id+" => "+doc.data());        
      });
    });
  }