我目前正在使用登录的webapp . 但是我的登出按钮有问题 . 注销按钮仅在您登录时显示,并在您注销时消失 .
那是我的Button(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');
}
}
基本上当我登录时,我希望“isLoggedIn”为“true” .
登录部分(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 回答
我相信您在成功登录后忘记更新isLoggedIn变量 .
试试这个
我建议你做的是你的服务(更好)或你的组件(没有那么好)一个getter方法,如:
private _isLogged:boolean = false;
this._isLogged = true; // < - sei it为true
然后在你的代码中:
希望它能帮到你!