3

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

Alexander Ciesielski
  • 10,506
  • 5
  • 45
  • 66
lesnar
  • 2,400
  • 7
  • 41
  • 72

2 Answers2

2

HTTP calls are asynchronous, that means that they don't finish immediately after being called.

The subscribe method, does two things:

  1. it 'starts' the call (in this case it sends the HTTP request)

  2. it calls the function that you pass as a parameter (callback function) after the call has completed, with the data that has been returned.

Alexander Ciesielski
  • 10,506
  • 5
  • 45
  • 66
1

Without subscribe() nothing will happen. Observables 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);
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567