gpt4 book ai didi

angular - 只运行一次订阅

转载 作者:太空狗 更新时间:2023-10-29 18:01:11 24 4
gpt4 key购买 nike

我只需要运行 userProfiles$.subscribe(async res => { 一次。但它可以无限运行。你能告诉我如何避免它吗?

这是 video of that issue :

.ts

async loginWithGoogle(): Promise<void> {
try {
const result = await this.afAuth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider());
const userId: string = result.additionalUserInfo.profile.id;
const userProfile: AngularFirestoreDocument<UserProfile> = this.fireStore.doc(`userProfile/${userId}`);
const userProfiles: AngularFirestoreCollection<UserProfile> = this.fireStore.collection('userProfile/', ref => ref.where('email', '==', result.additionalUserInfo.profile.email));
const userProfiles$: Observable<UserProfile[]> = userProfiles.valueChanges();

userProfiles$.subscribe(async res => { //problem is here
if (res.length == 0) {
await userProfile.set({
id: userId,
email: result.additionalUserInfo.profile.email,
creationTime: moment().format(),
lastSignInTime: moment().format()
});
} else {
await userProfile.update({
lastSignInTime: moment().format()
});
}
});
}
catch (err) {
console.log(err);
}
}

我已尝试将其转换为 promise,如下所示。但没有区别。也许我做错了?

 userProfiles$.map(async res => {
if (res.length == 0) {
await userProfile.set({
id: userId, email: result.additionalUserInfo.profile.email,
creationTime: moment().format(),
lastSignInTime: moment().format()
});
}
}).toPromise();

版本:

 "typescript": "2.4.2"
"rxjs": "5.5.2",

最佳答案

promise 方式:

userProfiles$.toPromise().then((res) => {
if (res.length == 0) {
await userProfile.set({
id: userId, email: result.additionalUserInfo.profile.email,
creationTime: moment().format(),
lastSignInTime: moment().format()
});
}
}).catch(err => {
// handle error
});

首先,您将其转换为 promise,然后通过 .then() 方法收听它并等待已解决的 promise。

可观察的.take(1)

userProfiles$.take(1).subscribe(async res => { //problem is here
if (res.length == 0) {
await userProfile.set({
id: userId,
email: result.additionalUserInfo.profile.email,
creationTime: moment().format(),
lastSignInTime: moment().format()
});
} else {
await userProfile.update({
lastSignInTime: moment().format()
});
}
});

注意 toPromise 方法不要忘记从 rxjs 运算符导入 toPromise 并且对于 take 你还应该导入 take 来自 rxjs 的方法

更新。 Angular 版本 >= 6

从 angular 6 开始,它需要 rxjs >= 6。现在像 take 这样的运算符现在可以导入并用在 .pipe() 方法中。 You can read more here

// somewhere at the top of file
import { take } from 'rxjs/operators';

userProfiles$.pipe(take(1)).subscribe(async res => { //problem is here
if (res.length == 0) {
await userProfile.set({
id: userId,
email: result.additionalUserInfo.profile.email,
creationTime: moment().format(),
lastSignInTime: moment().format()
});
} else {
await userProfile.update({
lastSignInTime: moment().format()
});
}
});

关于angular - 只运行一次订阅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47718919/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com