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
source share
3 answers

@estus. , . node_modules, rxjs, rxjs .

0

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

Response @angular/http :

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

, typescript:

npm i -g typescript@latest

, Observable , Rxjs, :

import { Observable } from 'rxjs/Observable';
0
source

Source: https://habr.com/ru/post/1687054/


All Articles