Reputation: 2480
I am having hard time understanding Angular2 Http(Observable) methods:
Here is my code:
login(username:string,password:string) {
let headers = new Headers();
this.createAuthorizationHeader(headers,username,password);
return this.http
.get(this.url,{headers:headers})
.map(this.extractData)
.catch(this.handleError).subscribe(e => console.log(e));
}
private extractData(res: Response) {
let body = res.json();
console.log(body);
return body.data || { };
}
My Question is : Why do we need subscribe method, if we can extract the data and everything else in a map method of an Observable ?
Thanks
Upvotes: 3
Views: 120
Reputation: 10834
HTTP calls are asynchronous, that means that they don't finish immediately after being called.
The subscribe
method, does two things:
it 'starts' the call (in this case it sends the HTTP request)
it calls the function that you pass as a parameter (callback function) after the call has completed, with the data that has been returned.
Upvotes: 2
Reputation: 657248
Without subscribe()
nothing will happen. Observable
s are lazy and only when subscribe()
, toPromise()
, or forEach()
is called they are executed.
You don't need to do anything in subscribe()
, it just needs to be called.
return this.http.get(this.url,{headers:headers})
.map(this.extractData)
.catch(this.handleError)
.subscribe(e => console.log(e));
or
return this.http.get(this.url,{headers:headers})
.subscribe(this.extractData, this.handleError);
Upvotes: 1