角度-身份验证服务中的变量并不总是更新

时间:2018-10-25 11:04:52

标签: javascript database angular

在我的项目中,我有一个身份验证服务,该服务与Nodejs后端联系并返回保存在用户cookie中的JWT。

export class AuthenticationService {

  baseUrl: string = 'xxxxx'

  accessToken: string;
  userProfile: any;
  loggedIn: boolean;
  loggedIn$ = new BehaviorSubject<boolean>(this.loggedIn);
  loggingIn: boolean;
  
  constructor(private http:HttpClient, private cookie: CookieService, private router: Router) { }

  login(username: string, password: string){
    console.log(`login invoked`)
    return this.http.post<any>(`${this.baseUrl}/users/login`, {email: username, password: password})
              .pipe(tap( res => this._getProfile(res), 
                         err => console.log(`Error login: ${err.error.message}`)))
  }

  private _getProfile(authResult) {
    console.log(`_getProfile invoked`)
    this.loggingIn = true;

    const httpOptions = { headers: new HttpHeaders( {'Authorization': authResult.idToken} ) };

    this.http.get(`${this.baseUrl}/users/login`,httpOptions)
      .toPromise()
      .then(profile => this.setSession(authResult,profile))
      .catch((err) => console.warn(`Error retrieving profile: ${err.error.message}`));
  }

  private setSession(authResult,profile) {
    console.log(`setSession invoked`)
    let expiredDate = new Date();
    expiredDate.setDate( expiredDate.getDate() + 7 );

    this.cookie.set('SESSIONID', authResult.idToken,expiredDate,'/');

    this.accessToken = authResult.idToken;
    this.userProfile = profile;

    this.setLoggedIn(true);
    this.loggingIn = false;
    this.router.navigate(['/'])
  }

  isAuthenticated() {
    return this.cookie.get('SESSIONID') ? true : false;
  }    

  renewToken() {
    let token = { idToken: this.cookie.get('SESSIONID')}
    this._getProfile(token);
  }

  setLoggedIn(value: boolean) {
    console.log(`actived setLoggedIn ${value}`)
    this.loggedIn$.next(value);
    this.loggedIn = value;
  }

  logout(){
    console.log('logout clicked')
    this.cookie.deleteAll('/');
    this.setLoggedIn(false);
  }
}

在我的家庭组件中,我检查是否保存了令牌并应用了一些逻辑,每个人都认为能正常工作

  load(){
    console.log('home - init')
    this.auth.isAuthenticated() && this.auth.renewToken();
  }

问题出在登录表单上。我正在将数据发送到服务器,并正确地修改了响应,它使auth服务中所有需要的过程变得复杂,并编写了cookie,但是由于某些原因,当我尝试访问变量loginIn时仍然是false;

  login(formData : FormGroup){
    this.auth.login(formData.value.email,formData.value.password).subscribe(res =>{
      this.toastr.success(`connected`);
    },error => this.toastr.error(error.error.message))
  }

这是进度的控制台日志。 加载应用程序,注销,登录并访问变量。

enter image description here

登录过程可以很好地解决我的问题,即在从登录表单登录的情况下,它不会更新auth-service的内部变量

0 个答案:

没有答案