2017-10-07 59 views
0

我在Angular 4執行router.navigateByUrl時無法更新自身的路由器菜單。無法刷新Angular 4中的路由器菜單

我在做什麼是非常基本的,我只是試圖隱藏登錄/註銷菜單,當用戶沒有/經過身份驗證。下面是我app.component.html

<h1> 
    {{ appName }} 
</h1> 

<nav> 
    <a *ngIf="!isLogged" routerLink="/login">Login</a> 
    <a *ngIf="isLogged" routerLink="/logout">Logout</a> 
</nav> 

<router-outlet></router-outlet> 

這裏是我的app.component.ts

import { Component } from '@angular/core'; 
import { AuthService } from './services/auth.service'; 
import { Router } from '@angular/router'; 

@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.css'] 
}) 
export class AppComponent { 
    isLogged: boolean; 

    // inject auth 
    constructor(private auth: AuthService, private router: Router) { } 

    ngOnInit() { 
     this.isLogged = this.auth.isLogged; 
     console.log('[app] islogged:' + this.auth.isLogged); 

     // redirect according to whether user logged in 
     if (this.isLogged) 
      this.router.navigateByUrl('/total'); 
     else 
      this.router.navigateByUrl('/login'); 
    } 
} 

正如你所知道的,LoginLogout是兩個單獨的部件。爲了證明這部分代碼是負責這個問題,以下是LogoutComponent::ngOnInit()

ngOnInit() { 
    // logout 
    this.auth.logout(); 

    // redirect to /login 
    this.router.navigateByUrl(''); 
} 

最後的命令能夠重定向到/但根據張貼在第一模板沒有更新菜單碼。

編輯: 這是用來登錄服務/註銷用戶:

import { Injectable } from '@angular/core'; 

@Injectable() 
export class AuthService { 
    isLogged: boolean = false; 
    token: string; 

    constructor() { } 

    login(token: string) { 
     // save token on login 
     this.isLogged = true; 
     this.token = token; 
    } 

    logout() { 
     // delete token on logout 
     this.isLogged = false; 
     this.token = ''; 
    } 
} 
+0

與控制檯登錄,用戶註銷時,你真的得到isLogged =假? – Wandrille

+0

@Wandrille是的,我試過了,它被設置爲False。 – h4k1m

+0

控制檯登錄你的app.component.html的ngInit是否給出false?或者在您的服務? – Wandrille

回答

1

改變它基於作爲路線上,

this.router.navigate(['/login']); 

雖然以上將解決您的導航問題。除此之外,實際問題出在您更新的方式isLogged變量在您的app.component.html

根據您現在的方式,只要在其他組件中進行更新,它就不會更新。所以你應該有shared service與變量subject,這將監視變化。

這樣的事情,

export class AppMessageQueuService { 
    authenticatedUserData: Subject<LoginInfo>; 
    constructor() { 
     this.authenticatedUserData = new Subject<LoginInfo>(); 
    } 
} 
+0

它也不起作用,菜單仍未更新。此外,參數應該是一個字符串而不是數組。 – h4k1m

+0

你是什麼意思菜單沒有更新「 – Sajeetharan

+0

this.router.navigate(['/ login'])是正確的方式來使用.navigate() – Wandrille