Angular您如何知道身份验证状态何时更改?

时间:2017-12-07 10:43:32

标签: angular authentication observable subscription

我目前正在使用登录的webapp工作。但是我的登出按钮有问题。注销按钮仅在您登录时显示,并在您注销时消失。

这就是我的按钮(menu-items.component):

<ul class="list-group">
  <li *ngIf="isLoggedIn" (click)="onLogout()">Logout</li>
</ul>

代码(menu-items.component):

import { Component, OnInit } from '@angular/core';
import { HttpService } from '../../http.service';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-menu-items',
  templateUrl: './menu-items.component.html',
  styleUrls: ['./menu-items.component.css']
})
export class MenuItemsComponent implements OnInit {
  isLoggedIn: boolean = false;
  constructor(private httpService: HttpService) {

  }

  ngOnInit() {

  }
  onSignout(){
    this.isLoggedIn = false;
    localStorage.removeItem('currentUser');
  }
}

基本上,当我登录时,我想要&#34; isLoggedIn&#34;是&#34;是&#34;。

登录部分(login.component):

 onSignin(){

    const username = this.loginForm.get('username').value;
    const password = this.loginForm.get('password').value;

    this.httpServie.sendDataLogin("grant_type=password&username=" + username + "&password=" + password)
      .subscribe(
        data => {
         this.token = JSON.parse(data["_body"]).access_token
         this.username = JSON.parse(data["_body"]).userName
         localStorage.setItem('currentUser', JSON.stringify({username: this.username, token: this.token}))

        },
        err => {
          if (err.error instanceof Error) {

            this.ServerErrorMsg = err.error.message;
          } else {

            const returnArray = [];
            this.ServerErrorMsg = JSON.parse(err._body).error_description + "\n";
          }
        }
      );
  }

登录部分正在运行!我将我的数据发送到我的API,作为回报,我得到了我的令牌。

但问题是如何告诉我现在登录的isLoggedIn布尔值?我想我需要一个可观察的东西或者用订阅来听,对吧? 我是Angular的新手,我真的不了解可观察量。有人可以帮帮我吗?

2 个答案:

答案 0 :(得分:0)

我建议你做的是你的服务(更好)或你的组件(没有那么好)一个getter方法,如:

private _isLogged:boolean = false;

isLoggedIn(){

 var local= localStorage.getItem('currentUser');
var token= JSON.Parse(local) as any;

return local && token && token.access_token;
}
onSignin(){

    const username = this.loginForm.get('username').value;
    const password = this.loginForm.get('password').value;

    this.httpServie.sendDataLogin("grant_type=password&username=" + username + "&password=" + password)
      .subscribe(
        data => {
         this.token = JSON.parse(data["_body"]).access_token
         this.username = JSON.parse(data["_body"]).userName
         localStorage.setItem('currentUser', JSON.stringify({username: this.username, token: this.token}));

this._isLogged = true; //&lt; - sei it to true

        },
        err => {
          if (err.error instanceof Error) {

            this.ServerErrorMsg = err.error.message;
          } else {

            const returnArray = [];
            this.ServerErrorMsg = JSON.parse(err._body).error_description + "\n";
          }
        }
      );
  }

然后在你的代码中:

<ul class="list-group">
  <li *ngIf="isLoggedIn()" (click)="onLogout()">Logout</li>
</ul>

希望它可以帮到你!

答案 1 :(得分:0)

我相信您在成功登录后忘记更新isLoggedIn变量。

试试这个

subscribe(
    data => {
     this.token = JSON.parse(data["_body"]).access_token
     this.username = JSON.parse(data["_body"]).userName
     localStorage.setItem('currentUser', JSON.stringify({username: this.username, token: this.token}))
this.isLoggedIn=true;
}