【发布时间】:2017-12-07 10:43:31
【问题描述】:
我目前正在开发一个登录的网络应用程序。但是我的注销按钮有问题。注销按钮仅应在您登录时显示,并在您注销时消失。
那是我的按钮(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 的新手,我不太了解 observables。有人可以帮帮我吗?
【问题讨论】:
标签: angular authentication observable subscription