angular - 隐藏基于 Authentication Angular 2 的链接

标签 angular authentication

我试图在不刷新页面的情况下基于用户身份验证立即隐藏 Navbar 链接

AppComponent.html

<div class="content">
    <md-toolbar>
        <md-icon>menu</md-icon>
        <span class="fill-space"></span>
        <button md-icon-button><md-icon>search</md-icon></button>
        <md-input-container>
            <input mdInput name="search" #search placeholder="Search">
        </md-input-container>

        <button md-raised-button color="primary" (click)="OpenLoginDialog()" *ngIf="!isAuthenticated">Login</button>
        <button md-raised-button (click)="OpenSignupDialog()" *ngIf="!isAuthenticated">Signup</button>
        <button md-raised-button (click)="Logout()" *ngIf="isAuthenticated">Logout</button>
    </md-toolbar>
</div>

认证服务

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;
    }
}
}

应用组件

    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();
    }
}

链接仅在页面刷新后隐藏,但我希望它在用户身份验证后立即隐藏

最佳答案

由于您的Authentication Service 中已经有一个函数,并且您已经将Authentication Service 注入(inject)到您的App.Component 中,请继续并使用一个简单的 *ngIf="authService.isLoggedIn()" 而不是在您的 App.Component 中创建一个局部变量,在那里数据会变得陈旧。

它在使用中看起来像这样:

<li *ngIf="authService.isLoggedIn()">
  <a [routerLink]="['/path1']">Path 1</a>
</li>
<li *ngIf="authService.isLoggedIn()">
  <a [routerLink]="['/path2']">Path 2</a>
</li>

可以将您在身份验证服务中使用的变量缩短为 *ngIf="authService.isLoggedin"

关于angular - 隐藏基于 Authentication Angular 2 的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43143429/

相关文章:

css - 从 JSON 文件或 typescript 文件定义 CSS 变量的方法?

javascript - ng-circle-progress 组件仅在属性 render OnClick 属性设置为 true 时才起作用

angular - markForCheck() 和 detectChanges() 有什么区别

authentication - 即使有测试号码,Flutter firebase auth 电话认证也会失败

angular - 使用 AngularJS 2 进行多平台开发

Angular - 使用 ID 的组件选择器

javascript - 如何在没有加密密码的情况下将 "auth"与 Adonis 一起使用?

ajax - 身份验证 header 不发送 JQuery Ajax

swift - 使用 Alamofire 进行身份验证的请求

python - user.is_staff 出现属性错误