Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/31.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 添加本地存储变量后未更新Angular2视图_Javascript_Angular - Fatal编程技术网

Javascript 添加本地存储变量后未更新Angular2视图

Javascript 添加本地存储变量后未更新Angular2视图,javascript,angular,Javascript,Angular,我有一个登录组件,当用户登录时,当前用户详细信息存储在本地存储变量中。因此,当登录成功时,将在本地存储变量中存储当前用户详细信息并导航到dashboard,我已使用本地存储变量获取用户详细信息并显示在网页标题中,但一旦我刷新页面,视图将不会更改 login() { this.authenticationService.login(this.model.username, this.model.password) .subscribe(

我有一个登录组件,当用户登录时,当前用户详细信息存储在本地存储变量中。因此,当登录成功时,将在本地存储变量中存储当前用户详细信息并导航到dashboard,我已使用本地存储变量获取用户详细信息并显示在网页标题中,但一旦我刷新页面,视图将不会更改

  login() {
    this.authenticationService.login(this.model.username, 
     this.model.password)
        .subscribe(
            data => {
                this.activeModal.dismiss();
                this.router.navigate(['dashboard']);
            },
            error => {
                this.alertService.error(error);
            });
 }
在职

  login(username: string, password: string) {
    return this.http.post('/api/authenticate', JSON.stringify({ username: 
     username, password: password }))
        .map((response: Response) => {
            // login successful if there's a jwt token in the response
            let user = response.json();
            if (user && user.token) {
                // store user details and jwt token in local storage to keep 
               user logged in between page refreshes
                localStorage.setItem('currentUser', JSON.stringify(user));
            }
        });
   }     

   getCurrentUser() {
    return JSON.parse(localStorage.getItem('currentUser'));
   }
在导航组件中

  constructor(private authenticationService: AuthenticationService) {
    getUser() {
      this.currentUser = this.authenticationService.getCurrentUser();
    }
  }
看法


乍一看一切都很好。本地存储在登录时是否正在保存您的数据?我认为您缺少服务“login”方法(在“map”回调中)中的“return”,因此在本地存储存储后将触发订阅:尝试在“localstorage.setItem('currentUser',JSON.stringify(user));'语句不要将锚元素用作按钮--!乍一看一切都很好。本地存储在登录时是否正在保存您的数据?我认为您缺少服务“login”方法(在“map”回调中)中的“return”,因此在本地存储存储后将触发订阅:尝试在“localstorage.setItem('currentUser',JSON.stringify(user));'语句不要将锚元素用作按钮--!
  <li *ngIf="currentUser"><a href="#">Welcome {{currentUser.firstName}}</a>
  </li>
  <li *ngIf="currentUser"><a href="#" (click)="logout()">Logout</a></li>
  <li *ngIf="!currentUser"><a href="#" (click)="openLoginModal()">Login</a>
  </li>
  <li *ngIf="!currentUser"><a href="#" (click)="openRegisterModal()">Register</a></li>
 ngDoCheck() {
    this.getUser();
 }