Angular 2:使用* ngIf和异步

时间:2018-04-17 09:05:34

标签: angular typescript

登录和退出有两个按钮。最初只有“登录”按钮可见。但经过身份验证后,“登录”按钮应更改为“注销”按钮。 但在我看来,为什么这不起作用,我该如何解决呢?

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});
        }
    )

  }

}

2 个答案:

答案 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>