user1354934
user1354934

Reputation: 8841

Is there a way to pass data out of the .subscribe in my angular2 service?

I've got the following function in my AuthService:

getToken() {
  this.http.post('myAuthEndpoint', { credentials })
  .subscribe((res) => {
    const token = res.headers.get('Authorization')
    localStorage.setItem('id_token', token);
  });
}

I want to return from getToken() the actual token value that I get back in the .subscribe. Is there a way to do that?

Upvotes: 2

Views: 59

Answers (1)

Sergey Sokolov
Sergey Sokolov

Reputation: 2839

If you need to do some other action when token is available you can do the following:

getToken() {
  return this.http.post('myAuthEndpoint', { credentials })
  .map((res) => {
    const token = res.headers.get('Authorization')
    return token;
  })
  .do((token) => {
    localStorage.setItem('id_token', token);
  });
}

// some other part of app
authService.getToken()
  .switchMap((token) => {
    // perform any desired action
  })
  .subscribe((result) => ...);

But beware that in this case calling getToken() without subsequent subscribe won't do anything.

Answer to comments

You have two services one provides token and other consumes it:

export class AuthService {
  private tokenSource = new ReplaySubject(1);
  private token$ = this.tokenSource.asObservable();

  constructor(private http: Http) {
    return this.http.post('myAuthEndpoint', { credentials })
    .map((res) => {
      let token = res.headers.get('Authorization')
      return token;
    })
    .do((token) => {
      localStorage.setItem('id_token', token);
    })
    .subscribe(this.tokenSource);
  }

  getToken() {
    return this.token$;
  }
}

export class RecentPhotosService {
  constructor(private authService: AuthService) {
    this.authService.getToken()
      .switchMap(token => {
        return this.getRecentPhotos(token);
      })
      .subscribe(photos => {...});
  }

  ...
}

Upvotes: 2

Related Questions