The 'toPromise' property does not exist in the type 'Observable <Response>
I searched for previous threads asking about this error message. From what I can find, there are two documented reasons for this error message.
Missing
import 'rxjs/add/operator/toPromise'
orimport 'import 'rxjs/add/operator/map'
Error in Visual Studio (which I do not use).
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 an 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, which also had rxjs, leading to duplication of rxjs inside the project.
+4
3 answers
HttpClient: https://angular.io/guide/http ( ).
:
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);
}
}
, , :
ngOnInit(): void {
this.movieService.getMovies()
.subscribe((movies: IMovie[]) => this.movies = movies);
}
+2