我尝试使用angularfire2
从firebase获取当前用户存储在实时数据库中 public user: any;
public userRef: any
public currentUser: any;
constructor(
public navCtrl: NavController,
public navParams: NavParams,
private fireAuth: AngularFireAuth,
private userProvider: UserProvider,
private fireDateBase: AngularFireDatabase
) {
this.currentUser = this.fireAuth.auth.currentUser.uid;
this.userRef = this.fireDateBase.object('CITYNAV_USERS/' + this.currentUser);
this.getCurrentUser();
}
ionViewDidLoad() {
}
public getCurrentUser(): void {
this.userRef.snapshotChanges().subscribe(action => {
this.user = action.payload.val();
console.log(this.user);
});
}
但出于某种原因,当this.user
告诉未定义但我不明白为什么。任何想法。
HTML
<ion-content padding>
<div class="wrapper-profile">
<img src="assets/imgs/logo-f.png" alt="">
<div class="wrapper-avatar">
<div class="avatar">
<img src="{{user.avatar}}" alt="avatar">
</div>
<button ion-button color="icons-color" clear>Cambiar imagen</button>
</div>
</div>
<div class="wrapper-profile-form">
<ion-item>
<ion-label>
<ion-icon name="ios-person-outline"></ion-icon> Nombre</ion-label>
<ion-input clearInput type="text" [(ngModel)]="user.name"></ion-input>
</ion-item>
<ion-item>
<ion-label>
<ion-icon name="ios-mail-outline"></ion-icon> Email</ion-label>
<ion-input clearInput type="email" [(ngModel)]="user.email"></ion-input>
</ion-item>
<ion-item>
<ion-label>
<ion-icon name="ios-lock-outline"></ion-icon> Password</ion-label>
<ion-input clearInput type="password" [(ngModel)]="user.password"></ion-input>
</ion-item>
<div class="profile-btn">
<button class="btn-edit" ion-button color="secondary" round>Editar informacion</button>
<button class="btn-logout" ion-button color="secondary" (click)="logOut()" round>Log Oout</button>
</div>
</div>
</ion-content>
这是从实时数据库获取用户对象后呈现用户对象的html。
控制台记录响应对象
Object {
avatar: "assets/imgs/avatar.jpg",
created: "Wed Nov 08 2017 16:54:53 GMT+0100",
email: "mianfrigo@gmail.com",
password: "Atenas10",
rol: "user",
userName: "Miguel Frias"
}
答案 0 :(得分:1)
现在,当您进行了适当的更改以将控制台日志放入回调(subscribe
)...
您可以在模板中初始化user
或使用*ngIf
,因为数据是异步的,视图会在数据到达之前呈现。或者您可以使用安全导航操作符,但安全导航操作符不能使用双向绑定,因此您需要将其拆分为单向绑定和ngModelChange
:
<input [ngModel]="user?.name" (ngModelChange)="user.name = $event"/>
或如上所述,您可以使用ngIf
并将模板包装在div中:
<div *ngIf="user">
<!-- code here-->
</div>
或者最简单的解决方案就是初始化对象。如果您的对象中没有嵌套对象,这将起作用。所以只需初始化您的用户:
user = {};
答案 1 :(得分:0)
您需要将console.log放在 subsrcibe
中,
public getCurrentUser(): void {
this.userRef.snapshotChanges().subscribe(action => {
this.user = action.payload.val();
console.log(this.user);
});
}