如何在ngrx/effects中使用承诺
问题描述:
我在Angular中将@ ngrx/store和@ ngrx/effects与Firebase身份验证一起使用。如何在ngrx/effects中使用承诺
这是构造:
constructor(
private actions: Actions,
private afAuth: AngularFireAuth,
private db: AngularFirestore,
private router: Router
) {}
这是效果:
@Effect()
getUser: Observable<Action> = this.actions
.ofType(authActions.GET_USER)
.map((action: authActions.GetUser) => action.payload)
.switchMap(payload => this.afAuth.authState)
.map(authData => {
if (authData) {
const user = new User(
authData.uid,
authData.displayName,
authData.email,
authData.photoURL
);
return new authActions.Authenticated(user);
} else {
return new authActions.NotAuthenticated();
}
})
.catch(err => Observable.of(new authActions.AuthError()));
此代码按预期工作,但我需要的是存储在公司的FireStore文档中,我可以检索其它值他们以这样的方式
[...]
if (authData) {
const userRef = this.db.firestore
.collection('users')
.doc(authData.uid)
.get()
.then(doc => {
const userData = doc.data();
return {
uid: userData.uid,
displayName: userData.displayName,
email: userData.email,
photoURL: userData.photoURL,
role: userData.roles
};
});
[...]
但由于它是一个承诺,我不能使用userRef
我在哪里使用user
。 有没有解决这个问题的方法?
答
只有一个问题来升级switchMap。
@Effect()
getUser: Observable<Action> = this.actions
.ofType(authActions.GET_USER)
.map((action: authActions.GetUser) => action.payload)
.switchMap(payload =>
this.afAuth.authState.switchMap(auth => {
if (auth) {
return this.db.doc<User>(`users/${auth.uid}`).valueChanges();
} else {
return Observable.of(null);
}
})
)
.map(authData => {
if (authData) {
const user = new User(
authData.uid,
authData.displayName,
authData.email,
authData.photoURL,
authData.roles
);
return new authActions.Authenticated(user);
} else {
return new authActions.NotAuthenticated();
}
})
.catch(err => Observable.of(new authActions.AuthError()));