ChatGPT解决这个技术问题 Extra ChatGPT

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

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

Normally, it's not a good idea to convert observables into promises. Observables are way more powerful
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 github.com/Microsoft/TypeScript/issues/… As it says, in Visual Studio 2015 you can fix this by updating your version of typescript via microsoft.com/en-us/download/details.aspx?id=48593

D
Dinistro

You need to add the operator like this:

import 'rxjs/add/operator/toPromise';

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


please update your answer for angular above version 2 (preferably 8 or 9)
S
Shai Barak

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

I have also updated the systemjs.config.js and followed the suggestions on this page. Now its fine.
hi MiHawk, what you did update in the systemjs.config.js?, I am also following the angular.io/docs/ts/latest/tutorial/toh-pt6.html, got stuck here
So what was the answer, it isn't stated what fixes this issue
I installed the latest version of TypeScript tools version 2.X microsoft.com/en-us/download/details.aspx?id=48593 and this fixed the problem -- but created 209 others. The rest of the fix was to exit Visual Studio and run >npm upgrade --save (as admin). a couple of packages failed to update, but when I start Visual Studio Bower/npm automatically updated the rest and all is good.
L
Liam

use this import at the beginning

import {Observable} from "rxjs/Rx";

really bad idea, this imports the entire RXJS library which is really big and will massively increase your page load times.
I don't think so.. we use import { component } from "@angular/core"; many places right so this should be also bad then ?
import {Observable} from 'rxjs/Observable'; is what you want ... this will import just Observable, if you do rxjs/Rx then it will import all of RxJS and only use the Observable, a real slow down. Remove all reference to rxjs/RX and watch the massive reduction in net requests and the speed up of page load speed.