Angular: 防止导航到不存在的 id 参数
Angular: Prevent navigating to non-existing id parameter
当我们有示例中的路径时,防止手动路由到 url 中不存在的参数的正确方法是什么:'edit/:id',其中 id 是参数?当然,如果我们输入一个匹配现有 url 的 id,它可以正常工作,但如果我们输入一个不存在的 id
,它就不起作用
我试过使用通配符路由,但这只适用于完整路由,没有参数。即使你在 /user/ 后面输入一些乱码作为参数,angular 仍然认为它是一个有效的路由。
这些是当前的路线:
{
path: '',
redirectTo: 'user',
pathMatch: 'full'
},
{
path: 'user',
component: UserComponent
},
{
path: 'user/:id',
component: UserEditComponent,
}
}
您可以使用路由解析器。这样你就可以先解析 getSomethingById,如果失败了就做你想做的。请注意,在示例代码中,我使用来自 RxJS 的 'of, Observable' 和来自 Rxjs/operators.
的 catchError
@Injectable()
export class GetSingleItemResolver implements Resolve<any>{
constructor(private apiService: APIService) {}
resolve(route: ActivatedRouteSnapshot): Observable<any> {
return this.apiService.getItemById(route.params['id']).pipe(
catchError(err => {
//Do what you want to do in the case that there is no item found with the ID
return of(null)
});
);
}
}
不要忘记将解析器添加到 providers 数组下的模块中。
在您的路由模块中,您需要像这样添加它:
{
path: 'detailPage/:id',
component: someDetailComponent,
resolve: {
singleItem: GetSingleItemResolver
}
}
如果您这样做,您可以从路由器获取 singleItem,因此您不必在组件本身中发出 getItemById 请求。这将已经由您的解析器解决。您可以像这样从路由器获取物品:
this.route.data.subscribe(data => {
this.singleItem = data['singleItem'];
});
希望对您有所帮助!
当我们有示例中的路径时,防止手动路由到 url 中不存在的参数的正确方法是什么:'edit/:id',其中 id 是参数?当然,如果我们输入一个匹配现有 url 的 id,它可以正常工作,但如果我们输入一个不存在的 id
,它就不起作用我试过使用通配符路由,但这只适用于完整路由,没有参数。即使你在 /user/ 后面输入一些乱码作为参数,angular 仍然认为它是一个有效的路由。
这些是当前的路线:
{
path: '',
redirectTo: 'user',
pathMatch: 'full'
},
{
path: 'user',
component: UserComponent
},
{
path: 'user/:id',
component: UserEditComponent,
}
}
您可以使用路由解析器。这样你就可以先解析 getSomethingById,如果失败了就做你想做的。请注意,在示例代码中,我使用来自 RxJS 的 'of, Observable' 和来自 Rxjs/operators.
的 catchError@Injectable()
export class GetSingleItemResolver implements Resolve<any>{
constructor(private apiService: APIService) {}
resolve(route: ActivatedRouteSnapshot): Observable<any> {
return this.apiService.getItemById(route.params['id']).pipe(
catchError(err => {
//Do what you want to do in the case that there is no item found with the ID
return of(null)
});
);
}
}
不要忘记将解析器添加到 providers 数组下的模块中。 在您的路由模块中,您需要像这样添加它:
{
path: 'detailPage/:id',
component: someDetailComponent,
resolve: {
singleItem: GetSingleItemResolver
}
}
如果您这样做,您可以从路由器获取 singleItem,因此您不必在组件本身中发出 getItemById 请求。这将已经由您的解析器解决。您可以像这样从路由器获取物品:
this.route.data.subscribe(data => {
this.singleItem = data['singleItem'];
});
希望对您有所帮助!