angular - Angular Resolver 不工作 没有 () 的提供者
问题描述
我在一个新项目中遇到了这个问题。我创建了一条路线:
const routes: Routes = [
{
path: '',
component: CategoriesComponent,
},
{
path: ':categoryId',
component: CategoryComponent,
resolve: CategoryResolver,
},
];
如您所见,它正在尝试使用解析器,如下所示:
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, Resolve, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
import { Category, CategoryService } from '@situlive/angular/data';
@Injectable({
providedIn: 'root',
})
export class CategoryResolver implements Resolve<Category> {
constructor(private categoryService: CategoryService) {}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Category> {
return this.categoryService.get(route.paramMap.get('categoryId'));
}
}
当我使用此代码时,出现错误:
未捕获(承诺):NullInjectorError:R3InjectorError(CategoriesModule)[()=> [->()=> [->()=> [->()=> [->()=> []:NullInjectorError: () => [没有提供者!
如果我像这样注释掉解析器:
const routes: Routes = [
{
path: '',
component: CategoriesComponent,
},
{
path: ':categoryId',
component: CategoryComponent,
//resolve: CategoryResolver,
children: [
{
path: 'criteria',
loadChildren: () => import('../criteria/criteria.module').then((m) => m.CriteriaModule),
},
{
path: 'feeds',
loadChildren: () => import('../feeds/feeds.module').then((m) => m.FeedsModule),
},
{
path: 'fields',
loadChildren: () => import('../fields/fields.module').then((m) => m.FieldsModule),
},
],
},
];
我不再收到错误,但显然没有解决任何问题。我的CategoryComponent中的代码如下所示:
ngOnInit(): void {
this.getCategory();
}
private getCategory(): void {
this.category = this.route.snapshot.data.category;
}
有谁知道为什么会发生这种情况?
解决方案
您首先需要修复您的路线定义。这可能是问题所在。尝试更改:
{
path: ':categoryId',
component: CategoryComponent,
resolve: CategoryResolver,
}
至 :
{
path: ':categoryId',
component: CategoryComponent,
resolve: {
category: CategoryResolver
},
}
因为解析需要是一个对象,而不是对解析器的直接引用,因为你可以在这里看到
推荐阅读
- c# - 如何将 KeyEventArgs 与角色进行比较?
- .net-core - 将 System.Web.Ui.WebControls 添加到分析器测试项目
- java - 提取pdf时在字母之间获取空格
- reactjs - 重复的字符串索引签名.ts(2374)
- regex - 组合正则表达式
- c# - 有没有办法在 Math.Net 上支持 0x0 矩阵?
- api - 在 Ionic 4 中使用 WooCommerce API v3 创建订单
- bash - 在“ answer=$( while !head -c 1 | grep -i '[ny]' ; do true ; done ) ”处支持 Ctrl+C / Ctrl+Z
- facebook-login - Facebook 应用程序重定向到错误的应用程序
- bash - UNIX 如何让我的脚本删除多个文件和通配符?