0

我在使用angular2中的Promise時遇到了問題。我已經導入了角度文檔建議的所有文件。但得到錯誤「無法找到名稱承諾」。以下是我的代碼:找不到名字Promise

import { Injectable } from '@angular/core'; 
import { Headers, Http, Response } from '@angular/http'; 
import 'rxjs/add/operator/toPromise'; 
@Injectable() 
export class StorefrontService { 
    private sfUrl = 'app/storefront/storefront.component.json'; // URL to mock json 
    constructor(private http: Http) { } 
    getSfItems(): Promise<any[]> { 
     return this.http.get(this.sfUrl) 
      .toPromise() 
      .then(this.extractData) 
      .catch(this.handleError); 
    } 
    private extractData(res: Response) { 
     let body = res.json(); 
     return body.data || {}; 
    } 
    private handleError(error: Response | any) { 
     // In a real world app, we might use a remote logging infrastructure 
     let errMsg: string; 
     if (error instanceof Response) { 
      const body = error.json() || ''; 
      const err = body.error || JSON.stringify(body); 
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`; 
     } else { 
      errMsg = error.message ? error.message : error.toString(); 
     } 
     console.error(errMsg); 
     return Promise.reject(errMsg); 
    } 
} 

是否需要從某處導入Promise對象?我試圖從rxjs庫導入,但它不起作用。

import { Promise } from 'rxjs/Promise'; 

任何想法爲什麼會發生這種情況?

+0

你得到你的瀏覽器或在你的IDE – lastWhisper

+0

錯誤我得到這個在IDE(VS代碼) –

回答

0

以下添加到導入部分:

import { Observable } from 'rxjs/Rx' 

this.http.get(...)將返回一個可觀察的,可通過增加toPromise()就像在你的代碼你做回一個承諾。進一步,你不必導入任何其他的承諾,因爲它是ES6中的默認類。

還看到:

希望這會有所幫助。

+0

嘿..我試過,但它仍然給同樣的錯誤的IDE。還有一件事。在我的tsconfig.json我有目標設置爲ES5 .. –

+0

將其設置爲ES6並忽略錯誤,它會編譯罰款 – lastWhisper