[英]How to add query params to route in guard and pass it to component in Angular 4?
I am using a route guard in my angular 4 app, and I would like to add a query param to the route if a condition satisfies and return true.我在我的 angular 4 应用程序中使用了一个路由守卫,如果条件满足并返回 true,我想向路由添加一个查询参数。
Here's the code I have been working on这是我一直在研究的代码
@Injectable()
export class ViewGuardService implements CanActivate {
constructor(private router: Router) { }
canActivate(activatedRoute: ActivatedRouteSnapshot, snapshot: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
if(!this.router.url.includes('/order-management')) {
//ADD PARAMS TO ROUTE OR PASS DATA TO COMPONENT HERE AND THEN RETURN TRUE
return true;
} else {
this.route.navigate['/login'];
return false;
}
}
}
Usually, to navigate to a route with params we can use it as this.router.navigate(['/order-management', activatedRoute.url[0].path], { queryParams: { moveToOrders: true }});
通常,要导航到带有参数的路由,我们可以将其用作
this.router.navigate(['/order-management', activatedRoute.url[0].path], { queryParams: { moveToOrders: true }});
. . But if I use this condition in the
if
condition, it turns out to an infinite loop of function calls.但是如果我在
if
条件中使用这个条件,结果是一个无限循环的函数调用。
So how do I pass params or data from the guard to the component?那么如何将参数或数据从警卫传递到组件呢? Please help me resolve this issue.
请帮我解决这个问题。
This is a bit hacky, but it works (Angular 11).这有点hacky,但它有效(Angular 11)。
@Injectable({
providedIn: 'root'
})
export class SetQueryParamGuard implements CanActivate {
constructor(
private _router: Router
) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean | UrlTree> {
const requiredQueryParam = route.queryParamMap.get('requiredQueryParam');
// Query param is set, no further action
if (requiredQueryParam) {
return of(true);
}
return of(
this._router
.parseUrl(state.url + `&requiredQueryParam=DEFAULT_VALUE`)
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.