Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why I got this.http.get(...).subscribe is not a function in angular2

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
like image 862
nbsp Avatar asked May 13 '16 11:05

nbsp


People also ask

What does .subscribe do in angular?

Normally Subscription means an arrangement to receive something. Similarly, in Angular applications Observables will be connected to observers and whenever they observe a new value or change in data, they will execute code with the help of Subscription and all the subscribed components will receive the updated outcome.

Can you subscribe to Observable multiple times?

It turns out that as the Observable is just a definition, let's remember that in a sense its something close to a function declaration, if we subscribe to it multiple times this means that each time a new HTTP request will be issued, one for each subscription.

What is HTTP in angular?

$http is an AngularJS service for reading data from remote servers.

What is Observable in angular stack overflow?

An observable is typically a programming construct that can be "watched" by other parts of the code, called the "observers".


1 Answers

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/

like image 59
David Pine Avatar answered Sep 25 '22 07:09

David Pine