-1

我在一个新项目中遇到了这个问题。我创建了一条路线:

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;
}

有谁知道为什么会发生这种情况?

4

1 回答 1

3

您首先需要修复您的路线定义。这可能是问题所在。尝试更改:

    {
        path: ':categoryId',
        component: CategoryComponent,
        resolve: CategoryResolver,
    }

至 :

    {
        path: ':categoryId',
        component: CategoryComponent,
        resolve: {
          category: CategoryResolver
        },
    }

因为解析需要是一个对象,而不是对解析器的直接引用,因为你可以在这里看到

于 2021-01-28T12:44:56.993 回答