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
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.
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.
$http is an AngularJS service for reading data from remote servers.
An observable is typically a programming construct that can be "watched" by other parts of the code, called the "observers".
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With