类型'Observable <Response>'上不存在属性'toPromise'

MiH*_*awk 73 rxjs typescript angular2-services angular

import { Headers, Http } from '@angular/http';

@Injectable()
export class PublisherService{

    private publishersUrl = 'app/publisher';

    constructor(private http: Http) { }

    getPublishers(): Promise<Publisher[]>{
        return this.http.get(this.publishersUrl)
                   .toPromise()
                   .then(response => response.json().data) 
                   .catch(this.handleError);
    }
}    
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

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

Din*_*tro 158

你需要像这样添加运算符:

import 'rxjs/add/operator/toPromise';
Run Code Online (Sandbox Code Playgroud)

这是您想要使用的每个rxjs运算符所必需的.

  • 请更新您对 Angular 版本 2 以上的答案(最好是 8 或 9) (3认同)

小智 10

尝试从'@ angular/http'向您的import语句添加'Response',如下所示:

import {Http, Headers, Response} from '@angular/http';
Run Code Online (Sandbox Code Playgroud)

另外我注意到你没有从角度核心导入Ingectable,尽管你使用@Injectable装饰器.

import { Injectable } from '@angular/core';
Run Code Online (Sandbox Code Playgroud)


ima*_*era 6

一开始就使用这个导入

__CODE__

  • 真的很糟糕,这会导入整个RXJS库,这个库非常大,会大大增加页面加载时间. (4认同)
  • 从'rxjs/Observable'导入{Observable}; 是你想要的...这将只导入Observable,如果你做rxjs/Rx然后它将导入所有的RxJS并且只使用Observable,一个真正的减速.删除对rxjs/RX的所有引用,并观察网络请求的大量减少和页面加载速度的加快. (4认同)