作者:求所以 | 来源:互联网 | 2023-02-07 20:44
我试图在没有页面刷新的情况下立即隐藏基于用户身份验证的Navbar链接
AppComponent.html
menu
验证服务
import { Injectable } from "@angular/core";
import { Observable } from "Rxjs";
import { Http, Headers } from "@angular/http";
import { User } from "./UserModel";
@Injectable()
export class AuthenticationService {
isLoggedin: boolean = false;
redirectUrl: string;
constructor(private http: Http) { }
login(model: User) {
debugger;
let headers = new Headers({ 'Content-Type': 'application/json' });
return this.http.post("/Account/Login", JSON.stringify({ model }), { headers: headers }).map(res => res.json()).map(res => {
debugger;
if (res.isSuccess) {
localStorage.setItem("auth_token", res.UserInfo);
this.isLoggedin = true;
}
return res.isSuccess;
});
}
logout(): void
{
localStorage.removeItem('auth_token');
this.isLoggedin = false;
}
isLoggedIn() {
debugger;
if (localStorage.getItem("auth_token") == null) {
this.isLoggedin = false;
return this.isLoggedin;
}
else {
return true;
}
}
}
App.Component
import { Component, OnInit } from "@angular/core";
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { Validate } from "./Custom.Validator";
import { MdDialog } from "@angular/material";
import { DialogComponent } from "./Dialog.Component";
import { LoginComponent } from "./Login.Component";
import { SignupComponent } from "./Signup.Component";
import { AuthenticationService } from "./Authentication.Service";
@Component({
selector: 'app-main',
templateUrl: "../App/App.html",
styles: [`div {
padding: 1rem;
}`]
})
export class AppComponent implements OnInit {
selectedEmoji: string;
isAuthenticated: boolean;
myForm: FormGroup;
constructor(private fb: FormBuilder, public dialog: MdDialog, public authService: AuthenticationService) { }
ngOnInit() {
this.myForm = this.fb.group({
state: ['', Validators.required],
zip: ['', [Validators.required, Validate]],
});
this.isLoggedIn();
}
openEmojiDialog() {
let dialog = this.dialog.open(DialogComponent);
dialog.afterClosed().subscribe(selection => {
if (selection) {
this.selectedEmoji = selection;
}
else {
}
});
}
OpenLoginDialog() {
let dialog = this.dialog.open(LoginComponent);
}
OpenSignupDialog() {
let dialog = this.dialog.open(SignupComponent);
}
Logout() {
this.authService.logout();
}
isLoggedIn()
{
this.isAuthenticated = this.authService.isLoggedIn();
}
}
链接仅在页面刷新后隐藏,但我希望它在用户身份验证后立即隐藏
1> Tyler Jennin..:
既然你已经在你的功能Authentication Service
,并且已注入Authentication Service
到你的App.Component
,继续前进,用一个简单的*ngIf="authService.isLoggedIn()"
,而不是在你创建一个局部变量App.Component
的数据会得到陈旧.
在使用中它看起来像这样:
Path 1
Path 2
可以缩短它以使用您在身份验证服务中已有的变量*ngIf="authService.isLoggedin"
.