无法在angular2和firebase中获取登录用户详细信息?

时间:2017-09-30 05:42:12

标签: angular firebase-authentication observable angularfire2 angular-services

我是angular and firebase的新手,假设我有一个像关注这样的服务,我使用angularfire2来处理数据库

import { Injectable } from '@angular/core';
import { AngularFireDatabase, FirebaseListObservable, 
FirebaseObjectObservable } from 'angularfire2/database';
import { AngularFireAuth } from 'angularfire2/auth';
import { AuthService } from '../../../services/auth.service';

@Injectable()
export class GroupsService {

user: User;

constructor(
 private afAuth: AngularFireAuth,
 private db: AngularFireDatabase,
)  {

this.afAuth.authState.subscribe( ( loggedInUser ) => {
  this.user = {
    email: loggedInUser.email,
    id: loggedInUser.uid
  };

  console.log(this.user) //getting logged in user info correctly
});
}

getGroups():FirebaseListObservable<any[]>{
 console.log(this.user);  //unable to get logged in user
 return this.db.list('groups',{
   query : {
     orderByChild: 'createdBy/email',
     equalTo: this.user.email
   }
  });
}

on getGroups()方法我根据登录的用户电子邮件地址获取群组。在该功能中,console.log(this.user);我收到undefined,请问如何解决此问题?

1 个答案:

答案 0 :(得分:0)

我通过此link

中提供的信息解决了这个问题
@Injectable()
export class GroupsService {

/**
* Observable for firebase user
*/
loggedInUser$: Observable<firebase.User>;


/**
* 
* @param authService 
* @param db 
*/
constructor(
private authService: AuthService,
private db: AngularFireDatabase,
) {

 this.loggedInUser$ = authService.user.share();
}

/**
* 
 */
getGroups():FirebaseListObservable<any>{

  return this.loggedInUser$.mergeMap( user => {

  let email = user.email;
  return this.db.list('groups', {
    query: {
      orderByChild: 'createdBy/email',
      equalTo: email
    }
  }) 
  }) as FirebaseListObservable<any[]>
 }
 }