簡體   English   中英

Angular 2:將* ngIf與async一起使用

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM