当我尝试在提供商的帮助下获取数据时,我遇到了问题。一切看起来还不错,但我仍然无法做到。
//Provider
import { Injectable } from '@angular/core';
import { AngularFireAuth } from 'angularfire2/auth';
@Injectable()
export class SomeProvider {
user: Observable<firebase.User>;
constructor(private firebaseAuth: AngularFireAuth) {
this.user = firebaseAuth.authState;
}
this.firebaseAuth.authState.subscribe(user => {console.log(user.uid)}); // i can get UID with this
........
但是当我在这里调用它时会返回undefined:
//menu.ts
import { SomeProvider } from '../../providers/some/some';
import { Component } from '@angular/core';
import { AngularFireAuth } from 'angularfire2/auth';
@IonicPage()
@Component({
selector: 'page-menu',
templateUrl: 'menu.html',
})
export class MenuPage {
constructor(private cfg: SomeProvider, private firebaseAuth: AngularFireAuth){}
ionViewDidLoad(){
console.log(this.cfg.user.uid); //returns undefined
.....
我已尝试使用firebase SDK但遇到同样的问题。
答案 0 :(得分:1)
您错过了firebase
所需的user: Observable<firebase.User>;
导入功能,如果您还没有,则应在SomeProvider
中导入:
import * as firebase from 'firebase/app';
另外,根据您的代码,user
是一个Observable,因此您需要订阅它:
export class MenuPage {
constructor(private cfg: SomeProvider, private firebaseAuth: AngularFireAuth){}
ionViewDidLoad(){
this.cfg.user.subscribe(user => console.log(user.uid));
<小时/> 可替换地:
@Injectable()
export class SomeProvider {
user: Observable<firebase.User>;
userId: string; // initialize
constructor(private firebaseAuth: AngularFireAuth) {
this.user = firebaseAuth.authState;
this.user.subscribe(user => this.userId = user.uid); // assign userId here
}
get getUserId(): string {
return this.userId;
}
然后在组件中:
export class MenuPage {
constructor(private cfg: SomeProvider, private firebaseAuth: AngularFireAuth){}
ionViewDidLoad(){
console.log(this.cfg.getUserId); // user id should be logged here