找不到名称 Promise

Cannot find name Promise

我在 angular2 中使用 Promise 时遇到问题。我已经按照 angular 文档的建议导入了所有文件。但是得到错误"Cannot find name 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';

知道为什么会这样吗?

将以下内容添加到导入部分:

import { Observable } from 'rxjs/Rx'

this.http.get(...) 将 return 一个可观察对象,它可以 return 通过添加 toPromise() 来实现承诺,就像您在代码中所做的那样。此外,您不必为 promise 导入任何其他内容,因为它是 ES6 中的默认值 class。

另见:

希望这对您有所帮助。