本文介绍了订阅承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Angular 7应用程序中,我具有下一个功能:

  getUserData(uid){返回this.fireStore.collection('users').doc(uid).valueChanges().subscribe(data => {this.writeCookie(数据)this.currentUser =数据;})} 

我想在另一种方法中使用此功能:

  someMethod(){...新的Promise(this.getUserData(uid)).then(()=> {...})...} 

但是我不能这样做,因为TypeScript抛出错误:

如何将 getUserData()方法转换为Promise,或改为使用 forJoin ?

谢谢.

解决方案

subscribe 将类型从 Observable 更改为 Subscription ,从而导致输入错误.

您可能想要的是在保留函数调用的同时将Observable转换为Promise.您可以通过以下方式来实现此目的:通过 tap 用管道传输Observable,然后用 toPromise 转换结果.像这样:

  getUserData(uid){返回this.fireStore.collection('users').doc(uid).valueChanges().pipe(点击(数据=> {this.writeCookie(数据)this.currentUser =数据;}),第一的()).承诺()} 

确保创建完整的管道,就像使用 first 运算符一样,否则Promise将永远无法解决.

您可以在消费者中忽略 new Promise(...).

In my Angular 7 application I have next function:

  getUserData(uid) {
    return this.fireStore.collection('users').doc(uid).valueChanges().subscribe(data => {
      this.writeCookie(data)
      this.currentUser = data;
    })
  }

And I want to use this function inside another method:

   someMethod() {
      ...
      new Promise(this.getUserData(uid))
         .then(() => {...})
      ...
   }

But I can't do this, because TypeScript throw an error:

How can I transform getUserData() method to a promise, or use forJoin instead?

Thanks in advance.

解决方案

subscribe changes the type from Observable to Subscription, thus causing the type error.

What you probably want is to convert your Observable to a Promise, while preserving the function call. You can do this, by piping the Observable through tap and then converting the result with toPromise. Like this:

getUserData(uid) {
  return this.fireStore.collection('users').doc(uid).valueChanges().pipe(
    tap(data => {
      this.writeCookie(data)
      this.currentUser = data;
    }),
    first()
  ).toPromise()
}

Make sure to create a completing pipe, like you can do with the first operator, otherwise the Promise will never resolve.

You can leave out new Promise(...) in your consumer.

这篇关于订阅承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 12:14