我有一个带有一些基本登录和注册路由的导航栏,但问题是,在主页('/')上有一个关于我们部分,我不想在登录时显示该部分('/ login')或signup('/ signup')页面。那么,如何仅在route('/')上显示该部分?
答案 0 :(得分:2)
您可以将路由器events
与已解析的urlAfterRedirects
结合使用,并放置在事件对象中:
export class NavComponent {
readonly showAbout$ = this.router.events.pipe(
filter((event) => event instanceOf NavigationEnd)
map((event) => this.canShowAbout(event.urlAfterRedirects)),
startWith(this.canShowAbout(this.router.url))
)
constructor(readonly router: Router) {}
canShowAbout(url: string): boolean {
return ['/login', '/signup'].every((path) => !url.startsWith(path)
}
}
,然后在您的组件中使用async
管道:
<nav>
<a routerLink="/home">Home</a>
<a *ngIf="showAbout$ | async" routerLink="/about">
About
</a>
</nav>
答案 1 :(得分:1)
在.ts
文件中
export class Page {
__URL:string = ""
constructor(router: Router) {
console.log(router.url); // This will print the current url
this.__URL = this.router.url;
}
}
在.html
文件中,您可以使用*ngIf
<div *ngIf="__URL === '/'">
// Render whatever you want
</div>
尝试用Location
代替Router
import { Location } from '@angular/common';
export class AppComponent implements OnInit {
constructor(private location: Location) {}
ngOnInit(){
console.log(this.location.path());
}
}
随时查看docs
如果它不起作用,请尝试以下
this.router.events
.pipe(
filter(e => e instanceof NavigationEnd)
)
.subscribe( (navEnd:NavigationEnd) => {
console.log(navEnd.urlAfterRedirects);
});