[英]Angular 2: use *ngIf with async
有两个按钮登录和注销。 最初只有“登录”按钮可见。 但是在身份验证之后,“登录”按钮应更改为“注销”按钮。 但是对我来说,为什么它不起作用,我该如何解决?
的HTML:
<div *ngIf="!(authService.userSignedIn$ | async)">
<button type="submit" class="btn btn-danger" data-toggle="modal" data-target="#exampleModal">
Login
</button>
</div>
<div *ngIf="(authService.userSignedIn$ | async)">
<button type="submit" class="btn btn-danger" (click)="logOut()">Logout</button>
</div>
Component.ts:
export class InfoComponent implements OnInit {
signInUser = {
email: '',
password: ''
};
@Output() onFormResult = new EventEmitter<any>();
constructor(protected authService:AuthService, private router:Router) {
}
ngOnInit() {
}
logOut(){
this.authService.logOutUser().subscribe(() => this.router.navigate(['/info']));
}
onSignInSubmit(){
$('#exampleModal').modal('hide');
this.authService.logInUser(this.signInUser).subscribe(
res => {
if(res.status == 200){
// loginForm.resetForm();
this.onFormResult.emit({signedIn: true, res});
this.router.navigate(['/profile']);
}
},
err => {
console.log('err:', err);
// loginForm.resetForm();
this.onFormResult.emit({signedIn: false, err});
}
)
}
}
使用BehaviorSubject
代替Subject
userSignedIn$:BehaviorSubject<boolean> = new BehaviorSubject(false);
您可以将ngIf-else与ng-template一起使用,如下所示:
<div *ngIf="!(authService.userSignedIn$ | async); else logout"> <button type="submit" class="btn btn-danger" data-toggle="modal" data-target="#exampleModal"> Login </button> </div> <ng-template #logout> <div> <button type="submit" class="btn btn-danger" (click)="logOut()">Logout</button> </div> </ng-template>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.