订阅承诺 [英] Subscription to promise
问题描述
在我的 Angular 7 应用程序中,我有下一个功能:
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(() => {...})
...
}
但我不能这样做,因为 TypeScript 会抛出错误:
But I can't do this, because TypeScript throw an error:
订阅"类型的参数不可分配给类型参数'(resolve: (value?: {} | PromiseLike<{}>) => void, reject: (reason?:任何) => 无效) => 无效'.类型订阅"不匹配签名 '(resolve: (value?: {} | PromiseLike<{}>) => void,拒绝:(原因?:任何)=> void):void'.ts(2345)
Argument of type 'Subscription' is not assignable to parameter of type '(resolve: (value?: {} | PromiseLike<{}>) => void, reject: (reason?: any) => void) => void'. Type 'Subscription' provides no match for the signature '(resolve: (value?: {} | PromiseLike<{}>) => void, reject: (reason?: any) => void): void'.ts(2345)
如何将 getUserData()
方法转换为 promise,或使用 forJoin
代替?
How can I transform getUserData()
method to a promise, or use forJoin
instead?
提前致谢.
推荐答案
subscribe
将类型从 Observable
更改为 Subscription
,从而导致类型错误.
subscribe
changes the type from Observable
to Subscription
, thus causing the type error.
您可能想要的是将 Observable 转换为 Promise,同时保留函数调用.你可以通过 tap
管道传输 Observable,然后用 toPromise
转换结果.像这样:
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()
}
确保创建一个完整的管道,就像您可以使用 first
运算符所做的那样,否则 Promise 将永远无法解析.
Make sure to create a completing pipe, like you can do with the first
operator, otherwise the Promise will never resolve.
您可以在消费者中省略 new Promise(...)
.
You can leave out new Promise(...)
in your consumer.
这篇关于订阅承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!