2017-11-17 1 views
1

Firebase 인증에서 Angular로 @ngrx/store 및 @ ngrx/effects를 사용하고 있습니다. 이것은 효과ngrx/effects에서 promise를 사용하는 방법

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 
       }; 
      }); 
[...] 

하지만 약속이기 때문에 나는을 사용할 수 없습니다3210 여기서 나는 user을 사용하고 있습니다. 이 문제의 해결책이 있습니까?

답변

0

레벨을 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())); 
관련 문제