2 回答

TA貢獻(xiàn)2037條經(jīng)驗 獲得超6個贊
您可以監(jiān)視路由器事件,特別NavigationEnd是將當(dāng)前路由分配給一個可觀察對象,然后在組件中檢查我們當(dāng)前所在的路由。
服務(wù):
import { Router, NavigationEnd } from "@angular/router";
import { filter, map } from "rxjs/operators";
currentRoute$: Observable<string>;
constructor(private router: Router) {
this.currentRoute$ = router.events.pipe(
filter(e => e instanceof NavigationEnd),
map((e: NavigationEnd) => e.url)
);
}
然后使用異步管道收聽 observable 并進(jìn)行檢查
*ngIf="(myService.currentRoute$ | async) === '/login'"
您也可以或許用includes,如果你需要檢查如果網(wǎng)址片段被包含在URL,然后你可以這樣做:
*ngIf="(myService.currentRoute$ | async).includes('login')

TA貢獻(xiàn)1847條經(jīng)驗 獲得超7個贊
在訂閱您的路線事件時,使用當(dāng)前更新服務(wù)上的行為主題
section$ = new BehaviorSubject(null);
在你的路線子
sections$.next(section);
然后在您的組件中,您使用異步管道收聽行為主題
section$ = this.service.section$;
并在模板中
<nav *ngIf="section$ | async as section">
<div *ngIf="section === 'navbar'">Something</div>
</nav>
每次行為主體發(fā)出時,section 變量都會神奇地更新。
添加回答
舉報