物业'然后'在Observable类型中不存在

时间:2016-12-06 00:03:40

标签: angular angular2-services

我是角色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]);
  }
}

这是ConnectionService:

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);
  }
}

如何解决此错误?

谢谢,

汤姆

3 个答案:

答案 0 :(得分:12)

Observable没有类似承诺的方法then。在您的服务中,您正在执行一个http调用,该调用返回一个Observable并将此Observable映射到另一个Observable。

如果您真的想使用promise样式的API,则需要使用toPromise运算符将Observable转换为promise。默认情况下,此运算符不可用,因此您还需要在项目中导入一次。

import 'rxjs/add/operator/toPromise';

使用promises是可以的,但有一些很好的理由直接使用Observable API。有关详细信息,请参阅此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将为您处理订阅。

答案 1 :(得分:0)

在之间添加.toPromise()以实现承诺

答案 2 :(得分:0)

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

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

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