我在 angular2 中使用 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';
知道为什么会这样吗?