2017-06-25 50 views
0

我有一個引導的導航欄,在導航欄的右側,我有一些鏈接,如登錄,註銷,註冊 我把它放在我的app.component.html .TS如何在angular2中的某些場景的路由後更新導航欄

<div class="navbar-collapse collapse"> 
// Here i check if user is authenticated, display : Hello [email protected] 
<ul *ngIf="user" class="nav navbar-nav navbar-right"> 
      //code in here 
</ul> 
// If user is not authenticated, display Login - Register 
<ul *ngIf="!user" class="nav navbar-nav navbar-right"> 
    <li><a routerLink="/register" id="registerLink">Register</a></li> 
    <li><a routerLink="/login" id="loginLink">Log in</a></li> 
</ul>  

在login.component.ts我打電話給我的Authen.Service.ts獲得令牌是商店上的localStorage

import { UrlConstants } from './core/common/url.constants'; 
import { LoggedInUser } from './core/domain/loggedin.user'; 
import { SystemConstants } from './core/common/system.constants'; 


@Component({ 
    selector: 'app-login', 
    changeDetection: ChangeDetectionStrategy.OnPush, 
    templateUrl: './login.component.html', 
    styleUrls: ['./login.component.css'] 
}) 
    export class LoginComponent implements OnInit { 
     public user: any; 
     private isLoggedIn = false; 


    loginUser(valid: boolean) { 
    this.loading = true; 
    if (valid) { 
     const userData = { 
     username: this.form.controls.username.value, 
     password: this.form.controls.password.value 
     } 

     this._authenService.login(userData.username, userData.password).subscribe(data => { 
     this.user = JSON.parse(localStorage.getItem(SystemConstants.CURRENT_USER)); 
     // If success redirect to Home view 
     this._router.navigate([UrlConstants.HOME]); 
     }, error => { 
     this.loading = false; 
     }); 

    } 
    } 
    ngOnInit() { 

    } 

} 

這裏是我的Authen.Service.ts

import { Injectable } from '@angular/core'; 
import { Http, Headers, RequestOptions, Response } from '@angular/http'; 
import 'rxjs/add/operator/map'; 

import { SystemConstants } from '../common/system.constants'; 
import { LoggedInUser } from '../domain/loggedin.user'; 


@Injectable() 
export class AuthenService { 

    constructor(private _http: Http) { 
    } 

    login(username: string, password: string) { 
    let body = "userName=" + encodeURIComponent(username) + 
     "&password=" + encodeURIComponent(password) + 
     "&grant_type=password"; 
    let headers = new Headers(); 
    headers.append("Content-Type", "application/x-www-form-urlencoded"); 
    let options = new RequestOptions({ headers: headers }); 

    return this._http.post(SystemConstants.BASE_API + '/api/oauth/token', body, options).map((response: Response) => { 
     let user: LoggedInUser = response.json(); 
     if (user && user.access_token) { 
     localStorage.removeItem(SystemConstants.CURRENT_USER); 
     localStorage.setItem(SystemConstants.CURRENT_USER, JSON.stringify(user)); 
     } 
    }); 
    } 

    logout() { 
    localStorage.removeItem(SystemConstants.CURRENT_USER); 
    } 

    isUserAuthenticated(): boolean { 
    let user = localStorage.getItem(SystemConstants.CURRENT_USER); 
    if (user != null) { 
     return true; 
    } 
    else 
     return false; 
    } 

這裏是我的app.component.ts

export class AppComponent implements OnInit { 

    // the user object got from localStore 
    ngOnInit() { 
     this.user = JSON.parse(localStorage.getItem(SystemConstants.CURRENT_USER)); 
     console.log(this.user); 
     } 
} 

我得到的問題是我不能更新導航欄右狀態改變(這仍然可以工作,我有令牌,但我必須刷新整個頁面來更新導航欄)

如何以角度方式更新導航欄?由於

+0

給定的HTML代碼是'login.compon ent.html'? –

+0

不,它在app.component.html中,我也有login.component.html,它在另一個模塊中,我想導航到主頁,它是app.component.html,如果登錄成功並更改導航欄,abc @ com – mkzpizza

+0

您是否向用戶提供了應用程序組件的價值?你可以附加app.component的代碼嗎? –

回答

0

我瞭解你的問題是:如何隱藏「登錄」鏈接位於主要成分用戶

簽署本人後,我能想到的解決方案類似以下內容:

裏面你AuthService你可以增加公共布爾成員「isLoggedIn」:

@Injectable() 
    export class AuthService { 
    isLoggedIn = false; 
    } 

您可以共享組件

登錄內部之間的服務組件,您可以登錄成功

login(){ 

this.auth.isLoggedIn = true 

} 

在你app.component後設置isLoggedIn爲true,您可以訂閱到路由器的NavigationEnd事件:

export class AppComponent { 
    constructor(
    private router: Router, private auth:AuthService){} 

    ngOnInit() { 
    this.router.events.subscribe(event => { 
     if (event.constructor.name === "NavigationEnd") { 
     this.isLoggedin = this.auth.isLoggedIn; 
     } 
    }) 
    } 

} 

,然後在應用組件模板就可以顯示「登錄!isLoggedin 「

這裏」帶* ngIf =菜單」 是plunker 希望它可以幫助...

相關問題