使用RxJ在Angular5中的服务之间传递值

时间:2018-04-20 15:22:36

标签: angular rxjs angular5

我正在尝试传递一个access_token,它在userService服务中声明,其值在register.component.ts中设置。然后我需要访问另一个服务(httpService)中access_token的值。我决定使用BehavioralSubject,但不知怎的,我无法在httpService中检索令牌的更新值。代码摘录如下。

User.service.ts - >在这里我声明了access_token

guests  (project_id)
videos  (guest_id)
emails  (video_id, id, opened, read_email,started_video, views)

and obvious on projects (id)

Register.component.ts - >在这里我成功地将值分配给access_token

 access_token = new BehaviorSubject<string>('');

Http.service.ts - &gt;这里我需要检索令牌的更新值

 onRegister(form){
    this.httpService.registerByEmail(this.email, this.password )
    .subscribe(
      response => {
        this.popupService.popupScreen.next('messenger');
        this.httpService.loginByEmail(this.email, this.password)
        .subscribe(response1 => {
          this.userService.access_token.next(response1['access_token']);
          console.log('access_token Component', this.userService.access_token);    --> here it console.logs the correct token
        },
        error => {
          console.log('error', error);
        }
      )
      },
      error => {
        if (error.error.status === false) {
          this.emailError =  error.error.errors.email;
          this.passwordError =  error.error.errors.password;
        };
      }

    )
  }

1 个答案:

答案 0 :(得分:0)

您需要始终将this.userService.access_token视为异步。

调用return this.access_token;时,尚未调用this.access_token = token

您需要链接此订阅才能使用令牌发出请求。

setLogin(): Observable<any[]> {

    const url = 'http://url';

    return this.userService.access_token
        .take(1)
        .concatMap((access_token) => {
            const httpHeaders = new HttpHeaders()
                .set('Authorization', 'Bearer ' + access_token);

            return this.httpClient.post<any[]>(url, { headers: httpHeaders });
        });
}

你也可以把事情包装成不同的方法,让事情看起来更好,但这对你有用。

take(1)将确保只发生一次。由于您使用BehaviorSubject作为令牌,它应该已经存在并立即发生。

concatMap()内进行调用,concatMap确保结果传播的方式与您刚返回this.httpClient.post()结果的方式相同。

编辑 - 注释:

调用setLogin()时,您需要订阅返回的值,否则不会被调用。

this.httpService.setLogin().subscribe();

如果您不想从该功能接收任何价值或知道何时完成,您也可以在.subscribe()之后concatMap()。您需要删除第一个return

RXJS管道是“懒惰的”,在订阅管道之前不会产生任何值。 access_token不会产生任何值,因此未调用服务器的post()