首页 > 解决方案 > 如何将承诺连接到这条链?

问题描述

我有一个检索一个用户的数据的功能。现在我想像这样在这个函数中获取 user_id:

    this.storage.get(USER_ID).then(val => {
             this.id = val;
)}

所以api知道它需要哪个用户的id。我必须插入的主要功能是:

ngOnInit() {
    this.subscription = this.authService.authenticationStateSubject.pipe(
      switchMap(isAuthenticated => {
        if (isAuthenticated) {
          return this.userService.getUserDetails(this.id);
        } else {
          return of(null);
        }
      }),
    ).subscribe(
      result => {
        if (result) {
          this.information = result;
          console.log(this.information);
        } else {
        }
      },
      error => {
      }
    );
  }

我试图将我的代码段放在后面,if (isAuthenticated) {但不知何故它不适用于最后两个括号。我真的可以连接这两个片段吗?

组合版

ngOnInit() {
    this.subscription = this.authService.authenticationState,
    from(this.storage.get(USER_ID))
    .pipe(
      switchMap(([isAuthenticated, id]) => {
        if (isAuthenticated) {
          return this.userService.getUserDetails(this.id);
        } else {
          return of(null);
        }
      }),
    ).subscribe(
      result => {
        if (result) {
          this.information = result;
          console.log(this.information);
        } else {
        }
      },
      error => {
      }
    );
  }

标签: javascriptangulartypescriptionic-framework

解决方案


使用 from 将你的 promise 转换为 observable 并使用 combineLatest 和 authenticationStateSubject

this.subscription = combineLatest(
  this.authService.authenticationStateSubject, 
  from(this.storage.get(USER_ID))
).pipe(
  switchMap(
    ([isAuthenticated, id]) => isAuthenticated ? this.userService.getUserDetails(id) : of(null)
  )
).subscribe(
  result => {
    // do stuff with result
  }
);

推荐阅读