【问题标题】:Property 'then' does not exist on type ObservableObservable 类型上不存在属性“then”
【发布时间】:2016-12-06 00:03:40
【问题描述】:

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

如何解决这个错误?

谢谢,

汤姆

【问题讨论】:

    标签: angular angular2-services


    【解决方案1】:

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

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

    import 'rxjs/add/operator/toPromise';
    

    使用 Promise 是可以的,但是直接使用 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();
    }
    

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

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

        GetUsersData() {
            const UsuariosCollection = this.afs.collection('usuarios').get();
        
            UsuariosCollection.toPromise().then((snapshot) => {
              snapshot.forEach((doc) => {
                console.log(doc.id+" => "+doc.data());        
              });
            });
          }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-09-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-11-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多