【问题标题】:How to connect a promise to this chain?如何将承诺连接到这条链?
【发布时间】:2020-03-19 08:51:05
【问题描述】:

我有一个检索一个用户数据的函数。现在我想像这样在这个函数中获取 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 => {
      }
    );
  }

我试图将我的 sn-p 放在 if (isAuthenticated) { 之后,但不知何故它不适用于最后两个括号。我真的可以连接这两个sn-ps吗?

组合版

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

【问题讨论】:

    标签: javascript angular typescript ionic-framework


    【解决方案1】:

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

    【讨论】:

    • 我真的不知道在哪里将 val 分配给我的 id。
    • combineLatest 发出一个输入 observables 的数组,id 已经在数组中。你不需要解开承诺,因为它是用 from 完成的。
    • 从我得到一个错误,它不存在类型布尔行为主题
    • 你将promise传递给from,而不是行为主体。
    • 我已经更新了我的问题,你的意思是这样吗?但是现在我有它声明但从未读取过的 for id,我从哪里获得值?
    猜你喜欢
    • 1970-01-01
    • 2019-05-24
    • 2016-12-30
    • 1970-01-01
    • 2018-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多