Search code examples
angularrxjsangular-promiseangular2-servicesangular2-observables

Cannot find name Promise


I am having trouble using Promise in angular2. I have imported all files as suggested by angular docs. But get the error "Cannot find name Promise". Below is my code:

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);
    }
}

Is the Promise object needs to be imported from somewhere? I tried importing from rxjs library but it did not work.

import { Promise } from 'rxjs/Promise';

Any idea why this is happening?


Solution

  • Add the following to the import section:

    import { Observable } from 'rxjs/Rx'
    

    this.http.get(...) will return an observable which can return a promise by adding toPromise() like your did in your code. futher you have not to import anything else for promise since it is a default class in ES6.

    see also:

    hope this helps.