无法刷新Angular 4中的路由器菜单
我在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');
}
}
正如你所知道的,Login
和Logout
是两个单独的部件。为了证明这部分代码是负责这个问题,以下是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 = '';
}
}
改变它基于作为路线上,
this.router.navigate(['/login']);
虽然以上将解决您的导航问题。除此之外,实际问题出在您更新的方式isLogged
变量在您的app.component.html
根据您现在的方式,只要在其他组件中进行更新,它就不会更新。所以你应该有shared service
与变量subject
,这将监视变化。
这样的事情,
export class AppMessageQueuService {
authenticatedUserData: Subject<LoginInfo>;
constructor() {
this.authenticatedUserData = new Subject<LoginInfo>();
}
}
它也不起作用,菜单仍未更新。此外,参数应该是一个字符串而不是数组。 – h4k1m
你是什么意思菜单没有更新“ – Sajeetharan
this.router.navigate(['/ login'])是正确的方式来使用.navigate() – Wandrille
与控制台登录,用户注销时,你真的得到isLogged =假? – Wandrille
@Wandrille是的,我试过了,它被设置为False。 – h4k1m
控制台登录你的app.component.html的ngInit是否给出false?或者在您的服务? – Wandrille