Property 'toPromise' does not exist on typ

2019-01-11 02:35发布

问题:

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

I am getting this error:

Property 'toPromise' does not exist on type 'Observable'.any

回答1:

You need to add the operator like this:

import 'rxjs/add/operator/toPromise';

This is needed for every rxjs operator you want to use.



回答2:

Try adding 'Response' to your import statement from '@angular/http' like this :

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

Also i noticed you don't import Ingectable from angular core although you use @Injectable decorator.

import { Injectable } from '@angular/core';


回答3:

use this import at the beginning

import {Observable} from "rxjs/Rx";



回答4:

For anyone else who stumbles on this (it was the top google link for me), see the below which comes from one of the linked answers

https://github.com/Microsoft/TypeScript/issues/8518#issuecomment-229506507

As it says, in Visual Studio 2015 you can fix this by updating your version of typescript via

https://www.microsoft.com/en-us/download/details.aspx?id=48593