登录和退出有两个按钮。最初只有“登录”按钮可见。但经过身份验证后,“登录”按钮应更改为“注销”按钮。 但在我看来,为什么这不起作用,我该如何解决呢?
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});
}
)
}
}
答案 0 :(得分:0)
使用BehaviorSubject
代替Subject
userSignedIn$:BehaviorSubject<boolean> = new BehaviorSubject(false);
答案 1 :(得分:-1)
您可以将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>