Property 'toPromise' does not exist on type 'Observable<Response>'

AngularTypescriptRxjsAngular2 Services

Angular Problem Overview


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

Angular Solutions


Solution 1 - Angular

You need to add the operator like this:

import 'rxjs/add/operator/toPromise';

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

Solution 2 - Angular

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';

Solution 3 - Angular

use this import at the beginning

import {Observable} from "rxjs/Rx";

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAbhishek SharmaView Question on Stackoverflow
Solution 1 - AngularDinistroView Answer on Stackoverflow
Solution 2 - AngularShai BarakView Answer on Stackoverflow
Solution 3 - Angularimal hasaranga pereraView Answer on Stackoverflow