angular - Observable 类型不存在属性 'then'

标签 angular angular2-services

我是 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 的方法。在您的服务中,您正在执行一个返回 Observable 的 http 调用,并将此 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 将为您处理订阅。

关于angular - Observable 类型不存在属性 'then',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40985605/

相关文章:

http - .then 处理程序被乱序调用

javascript - Angular 4嵌套formArray/formGroup将数据库查询中的值放回表单中

angular - 从 angular 2 中的对象访问特定值

javascript - angular 2 服务不调用 php 文件

使用 .asObservable() 的 Angular 2 单元测试 (TestBed) 服务

javascript - 循环遍历 2 个数组,并将一个数组中的值分配给第二个数组的每个匹配对象

angular - 当 reducer 更改切片时,Ngrx 选择器未触发

angular - 如何在两个模块之间共享服务 - @NgModule 在 Angular 上而不是在组件之间?

angular - 如何将数据从 MatBottomSheet 返回到其父组件?

javascript - Angular 2 - 加载路由组件,然后返回到上一个组件