Using observables like resolve: process data in service


#1

I am trying to figure out observables right now, and I have a simple problem. How do I process data within my User Service and pass data to my login component? For example, I would like to save a token in local storage etc. If I include .subscribe in my User Service after .map, then I get an error when I use .subscribe in my login component.

In my User Service:

  login(username, password) {
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    return this.http.post(authUrl,JSON.stringify({username:username, password:password}),options)
      .map(res => res.json())
      // process tokens etc here
  }

In my login component:

  login(){
    this.userData.login(this.credentials.username, this.credentials.password)
      .subscribe(
        data => this.nav.push(TabsPage, {}),
        err => console.log("error", err)
      )
  }

#2

I’m pretty sure you want the “do” operator.

It would look something like:

login(username, password) {
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    return this.http.post(authUrl,JSON.stringify({username:username, password:password}),options)
          .map(res => res.json())
          .do(jsonRes => {
                  // process tokens etc here  
          })      
}