[英]Angular2 route guard returning Observable<bool>, how to handle errors
[英]How to use an Observable in Angular route guard?
在我的角度路由模塊中,當默認頁面(現在處於某種條件下)要確定要導航的路線時,我正在使用基本導航。 這就是我的應用程序路由外觀。
{ path: '', redirectTo: 'home1', canActivate: [homepageGuard], pathMatch: 'full' }, { path: 'home1', loadChildren: './lazyloadedmodule1' }, { path: 'home2', loadChildren: './lazyloadedmodule2' }, { path: 'home3', loadChildren: './lazyloadedmodule3' }, { path: 'basehome', loadChildren: './lazyloadedmodule4' }
現在在我的路由守衛中,我這樣調用訂閱。
canActivate(): Observable<any> | boolean { return this._myService.getCurrentApp().subscribe( (r) => { if(r === 'app1'){ //navigate to app1homepage } else if (r === 'app2') { //navigate to app2homepage } else { // navigate to base homepage } }, (e) => { console.log(e); return false; } ); }
這就是服務在調用API時的外觀。
public getCurrentApp(): Observable<any> { return this.http.get(this.apiBaseUrl + 'getApp').pipe( catchError((err: HttpErrorResponse) => { return throwError(err.error.errorMessage); })); }
首先,routeguard不會將值作為訂閱,因為我認為它只是一個布爾值,但是我將以字符串形式返回響應。 如何確保在首頁加載期間調用API並相應地對其進行重定向?
我提出這樣的建議。 使用服務並返回true / false和導航。
canActivate(): Observable<any> | boolean { return this._myService.getCurrentApp() pipe( tap((response) => { if(r === 'app1'){ this.router.navigate([...]); } else if (r === 'app2') { this.router.navigate([...]); } else { this.router.navigate([...]); } }), map(() => false), catchError((e)=> of(false)) ) } }
坦率地說,這不是解決此類問題的最佳解決方案。 我認為更好的方法是為將執行API請求的不同路徑創建不同的AuthGuard,並檢查是否允許其進入特定的路由。 然后僅返回false或true。
您的警衛不應該訂閱可觀察的東西,路由器會這樣做。
因此,您基本上需要返回一個可觀察值,該值返回true或false。
如果您要重新路由,那么您顯然永遠不會返回true。
canActivate(): Observable<boolean> {
return this._myService.getCurrentApp().pipe(
tap(r => {
if(r === 'app1'){
//navigate to app1homepage
} else if (r === 'app2') {
//navigate to app2homepage
} else {
// navigate to base homepage
}
}),
catchError(r => of(false))
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.