Angular 2:Observables无法登录

时间:2017-05-15 10:55:35

标签: angular typescript rxjs

您好我正在尝试在导航栏中显示登录用户的用户名,这是有效的,但在您登录或注销后它不会立即更新。为了完成这项工作,我开始使用rxjs的Subject和Observable,这在我注销时有效但在我登录时没有。我仍然很有角度,有人知道问题是什么吗?

navbar.component.ts

  constructor(
    private authService: AuthService,
    private router: Router,
    private flashMessage: FlashMessagesService,
    private toastrService: ToastrService
  ) {
    this.auth = authService;
    authService.isLoggedIn().subscribe(
      status => {
        if(status == false) {
          this.user = null;
        } else {
          this.authService.getProfile().subscribe(profile => {
            this.user = profile.user;
          })
        }
      }
    )
  }

auth.service.ts

  private logger = new Subject<boolean>();

  isLoggedIn(): Observable<boolean> {
    return this.logger.asObservable();
  }

  setLoginLogger(status){
    this.logger.next(status)
  }

  logout(){
    this.authToken = null;
    this.user = null;
    localStorage.clear();
    this.logger.next(false);
  }

  authenticateUser(user){
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    return this.http.post('http://localhost:3000/users/authenticate', user, {headers: headers})
          .map(res => res.json());
  }

  storeUserData(token, user){
    localStorage.setItem('id_token', token);
    localStorage.setItem('user', JSON.stringify(user));
    this.authToken = token;
    this.user = user;
  }

login.component.ts

 onLoginSubmit(){
    const user = {
      username: this.username,
      password: this.password
    }

    this.authService.authenticateUser(user).subscribe((data) => {
      if(data.success){
        this.authService.storeUserData(data.token, data.user);

        if(localStorage.getItem('id_token')){
          this.authService.setLoginLogger(true);
          this.router.navigate(['']);
          this.toastrService.success('Hello world!', 'Toastr fun!');
        }

      } else {
        this.toastrService.success('Hello world!', 'Toastr fun!');

        this.router.navigate(['login']);
      }
    })
  }

2 个答案:

答案 0 :(得分:0)

您需要使用 ChangeDetectorRef 来反映 navbar.component.ts 中的更改。

import { Component, ChangeDetectorRef} from '@angular/core';

constructor(
private authService: AuthService,
private router: Router,
private flashMessage: FlashMessagesService,
private toastrService: ToastrService,private changeDetectorRef: ChangeDetectorRef) {
this.auth = authService;
authService.isLoggedIn().subscribe(
  status => {
    if(status == false) {
      this.user = null;
    } else {
      this.authService.getProfile().subscribe(profile => {
        this.user = profile.user;
        //reflect the changes
         this.changeDetectorRef.detach();
         setInterval(() => {
          this.changeDetectorRef.detectChanges();
         }, 1000);
      })
    }
  }
)
 }

希望它有所帮助!!

答案 1 :(得分:0)

我找到导致问题的原因,我不得不删除我的组件中的提供程序,因为它已经提供给我的 app.module.ts