从 Promise Angular4 内部更新视图中的变量
Update variable in view from inside promise Angular4
我有以下代码:
<div class="row" *ngIf="!isFacebookAuth">
<div class="col-md-8 col-md-offset-2 text-center">
<p>To start using Gili-go, simply login using facebook, give us a contact number for our drivers, and you're good to go!</p>
<button class="btn btn-primary" (click)="loginFacebook()"><i class="fa fa-facebook"></i> Login With Facebook</button>
</div>
</div>
<div class="row" *ngIf="isFacebookAuth">
<p>test </p>
<div>
然后我的控制器:
loginFacebook(){
this.userService.signInWithFaceBook()
.then((data) => {
this.isFacebookAuth = true;
console.log(data);
})
.catch(error => console.log(error));
}
登录功能使用firebase2,其中返回一个promise。
控制器中的值按应有的方式更改,但是由于某种原因,视图端的 isFacebookAuth 变量未更新,并且两个 Div 根本没有更改。
我认为这是因为变量在 firebase.But 返回的承诺中发生了变化,我该如何解决这个问题?
您可以通过调用 ChangeDetectorRef class 的 detectChanges()
来触发更新视图的更改检测。
在你的组件中,
import { ChangeDetectorRef } from '@angular/core';
constructor(private ref: ChangeDetectorRef) {}
loginFacebook(){
this.userService.signInWithFaceBook()
.then((data) => {
this.isFacebookAuth = true;
console.log(data);
this.ref.detectChanges(); // triggers another change detection cycle
})
.catch(error => console.log(error));
}
我有以下代码:
<div class="row" *ngIf="!isFacebookAuth">
<div class="col-md-8 col-md-offset-2 text-center">
<p>To start using Gili-go, simply login using facebook, give us a contact number for our drivers, and you're good to go!</p>
<button class="btn btn-primary" (click)="loginFacebook()"><i class="fa fa-facebook"></i> Login With Facebook</button>
</div>
</div>
<div class="row" *ngIf="isFacebookAuth">
<p>test </p>
<div>
然后我的控制器:
loginFacebook(){
this.userService.signInWithFaceBook()
.then((data) => {
this.isFacebookAuth = true;
console.log(data);
})
.catch(error => console.log(error));
}
登录功能使用firebase2,其中返回一个promise。
控制器中的值按应有的方式更改,但是由于某种原因,视图端的 isFacebookAuth 变量未更新,并且两个 Div 根本没有更改。
我认为这是因为变量在 firebase.But 返回的承诺中发生了变化,我该如何解决这个问题?
您可以通过调用 ChangeDetectorRef class 的 detectChanges()
来触发更新视图的更改检测。
在你的组件中,
import { ChangeDetectorRef } from '@angular/core';
constructor(private ref: ChangeDetectorRef) {}
loginFacebook(){
this.userService.signInWithFaceBook()
.then((data) => {
this.isFacebookAuth = true;
console.log(data);
this.ref.detectChanges(); // triggers another change detection cycle
})
.catch(error => console.log(error));
}