使用 Ionic 在 angularfire2 中获取当前用户的数据

Get current user's data in angularfire2 with Ionic

我正在搜索如何使用服务获取用户数据

users.services.ts

import { AngularFire, AuthProviders, AuthMethods, FirebaseListObservable}     


export class Users {
   uid :string = '8fbEOShqIigfA4u84cyvJcLkv5u1';

    constructor(public af: AngularFire) {}

    getUserObservable(){
        return this.af.database.object('/users/' + this.uid);
    }
}

这是我的 home.ts

import { Users } from '../../services/users.service';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  user: any;
  isAuthenticated: boolean = true;

  constructor(private userService: Users) {}

  ngOnInit(){
    this.userService.getUserObservable().subscribe((userObject) => {
      this.user = userObject;
      console.log("result : ", this.user);
    });
  }

}

在控制台中我得到:

result :  Object {imgLink: "blabla.jpg", money: 0, score: 0, uid: "8fbEOShqIigfA4u84cyvJcLkv5u1", username: "Luis Willnat"…}

但在离子视图中:

Cannot read property 'money' of undefined

我认为这是因为一些异步的东西(我练习得不够好)但不知道是什么..

非常感谢您的帮助:)

您需要以不同方式设置代码。通常,当服务包装异步调用时——任何异步调用,而不仅仅是 Firebase 的——它的方法应该return observables,而不是 observables 发出的值.

即使您愿意,也不方便(或不可能)尝试 return 包裹在 observable 中的值,因为它们仅在 observable 发出时可用,而您无法控制何时发出会。

根据这些准则,您的代码将变为:

@Injectable()
export class UserService {
  constructor(public af: AngularFire) {}
  getUser() {
    // Return the observable. DO NOT subscribe here.
    return this.af.auth;
    // Hint: you could also transform the value before returning it:
    // return this.af.auth.map(authData => new User({name: authData.name}));
  }
}

然后,在您的组件中或您需要的任何地方,您订阅以获取用户:

ngOnInit() {
  this.userService.getUser()
    .subscribe(user => this.user = user);
}