我在一个新项目中遇到了这个问题。我创建了一条路线:
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;
}
有谁知道为什么会发生这种情况?