7
votes

My code is

    import 'rxjs/Rx';
    ...
    let _this = this;
    return new Promise(function(resolve, reject) {
        _this.http[method](url, data, {
            headers: headers
        })
        .toPromise()
        .then(
            (data) => {
                resolve(data);
            },
            error => {
                reject(error);
            }
        );
    });

The "subscribe" not come from my code, looks like it's angular original something.

Error message:

EXCEPTION: Error: Uncaught (in promise): TypeError: _this.http.get(...).subscribe is not a function
1
You don't need let _this = this if you use (resolve, reject) => { instead. You don't need new Promise(...) when you use toPromise(). Just return this.http[method](url, data, { headers: headers }) .toPromise(); should do the same.Günter Zöchbauer
Definitely agreed with Günter! Regarding your error, which version of Angular2 do you use? I made a try with beta17 but I don't have the error: plnkr.co/edit/TPy2UVEE8EE4MLTlf8yc?p=preview.Thierry Templier
Becoz I have few steps in "then", install angular with ionic betanbsp

1 Answers

2
votes

You are combating the Angular2 initiative of porting over from the promise based asynchronous paradigm to the reactive-extensions alternative. Instead of using a promise, use the subscribe instead:

import 'rxjs/Rx';
...
invoke<T>(onNext: (data: T) => void, onError: (error: any) => any) {
    this.http[method](url, data, {
        headers: headers
    })
    .map(response => response.json() as T)
    .subscribe(onNext, onError);
});

I wrote a blog post about this too.

https://ievangelist.github.io/blog/angular-2-http/