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

Viewed 1097

I searched previous threads asking about this error message. From what I can find there are two documented causes for this error message.

  1. Missing import 'rxjs/add/operator/toPromise' or import 'import 'rxjs/add/operator/map'

  2. Error with Visual Studio (which I am not using).

This is the code in question

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

import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';

import { Event } from './event';

@Injectable()
export class EventService {

  private eventsUrl = 'api/events'; // URL to web api
  private headers = new Headers({'Content-Type': 'application/json'});

  constructor(private http: Http) { }

  getEvents(): Promise<Event[]> {
    return this.http.get(this.eventsUrl)
               .toPromise()
               .then(response => response.json().data as Event[])
               .catch(this.handleError);
  }
}

The code above gives me the error Property 'toPromise' does not exist on type 'Observable<Response>'

EDIT: Thanks to @estus I found out that I installed one of the packages incorrectly. The package has its own node_modules that also had rxjs resulting in duplicates rxjs inside the project.

3 Answers

You may want to instead follow the updated docs on using the new HttpClient: https://angular.io/guide/http (though they don't have the code in a service).

Service

The code in the service would then look like this:

import { Injectable } from '@angular/core';
import { HttpClient} from '@angular/common/http';

import { Observable } from 'rxjs/Observable';

import { IMovie } from './movie';

@Injectable()
export class MovieService {
    private moviesUrl = './api/movies/movies.json';

    constructor(private http: HttpClient) { }

    getMovies(): Observable<IMovie[]> {
        return this.http.get<IMovie[]>(this.moviesUrl);
    }
}

Component

And the component code calling this method would look like this:

ngOnInit(): void { 
    this.movieService.getMovies()
        .subscribe((movies: IMovie[]) => this.movies = movies);
}

Consider importing Response from @angular/http like this :

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

Maybe also upgrading to the latest version of typescript could help:

npm i -g typescript@latest

A side note also it is better to import Observable alone like this from Rxjs rather than the entire library:

import { Observable } from 'rxjs/Observable';

Thanks to @estus. I found out that I installed one of the packages incorrectly. The package has its own node_modules that also had rxjs resulting in duplicates rxjs package inside the project.

Related