有没有办法在我的angular2服务中从.subscribe传递数据?

时间:2016-12-21 23:27:33

标签: javascript angular rxjs

我的AuthService中有以下功能:

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

我想从getToken()返回.subscribe中返回的实际令牌值。有没有办法做到这一点?

1 个答案:

答案 0 :(得分:2)

如果您需要在令牌可用时执行其他操作,则可以执行以下操作:

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) => ...);

但请注意,在这种情况下,在没有后续getToken()的情况下调用subscribe将无法执行任何操作。

回复评论

您有两个服务,一个提供令牌,另一个消费它:

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 => {...});
  }

  ...
}