仅在几秒钟后this.loggedIn设置为true,如何等待其值

时间:2019-02-09 07:39:54

标签: angular

在控制台中的ts文件中,记录this.loggedIn,当我输入正确的用户名和密码时,访问令牌存储在本地存储中,并在控制台中首先打印false值,然后在2秒钟后打印true控制台。

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject } from 'rxjs';

@Injectable({
    providedIn: 'root'
})
export class ApiService {

    checkStatus = new BehaviorSubject<boolean>(false);
    isUserLoggedIn = this.checkStatus.asObservable();

    readonly loginUrl= 'http://********';

    constructor(private http: HttpClient) { }

    checkLogin() {
        const access_token = localStorage.getItem('access_token');
        if(access_token) 
        {
            this.checkStatus.next(true);
        } else {
            this.checkStatus.next(false);
        }
    }

    loginUser(user: any) {
        return this.http.post(this.loginUrl, user)
        .subscribe((success1: any) => {
            if(success1) {
                localStorage.setItem('access_token', success1.success.token);
                // localStorage.setItem('user', JSON.stringify(success.success.token));
                return true;
            }
        });
    }

}

这是我的提示:

this.api.loginUser(user);
this.api.isUserLoggedIn.subscribe( (val) => {
    // this.loggedIn = val.valueOf();
    this.loggedIn = val;
    console.log(this.loggedIn);
    this.route.navigate(['/dashboard']);
});

1 个答案:

答案 0 :(得分:0)

它首先返回false,因为当时用户未登录,val返回false,但是当用户登录时,将发出新值,这是正确的。试试这个。

loginUser(user: any) {
    return this.http.post(this.loginUrl, user);
  }

当用户登录时

this.api.loginUser(user).subscribe( () => {
     this.api.isUserLoggedIn.subscribe( (val) => {
     localStorage.setItem('access_token', success1.success.token);
     this.loggedIn = val;
     console.log(this.loggedIn);
     this.route.navigate(['/dashboard']);
  });
});