隐藏基于Authentication Angular 2的链接

时间:2017-03-31 14:40:24

标签: 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;
    }
}
}

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 个答案:

答案 0 :(得分:5)

由于您的Authentication Service已经有了一项功能,并且您已将Authentication Service注入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"