我有一个检索一个用户数据的功能。现在,我想像这样使用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 => {
      }
    );
  }

最佳答案

使用from将您的promise转换为可观察的,并结合使用authenticateStateSubject和CombineLatest

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
  }
);

09-13 11:37