代码之家  ›  专栏  ›  技术社区  ›  r3plica

角度解析程序不工作没有()的提供程序

  •  0
  • r3plica  · 技术社区  · 5 年前

    我在一个新项目中遇到了这个问题。

    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:没有()的提供程序=>[!

    如果我这样注释解析程序:

    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),
                },
            ],
        },
    ];
    

    我不再得到错误,但显然没有解决任何问题。 我的代码在我的 类别成分 就像这样:

    ngOnInit(): void {
        this.getCategory();
    }
    
    private getCategory(): void {
        this.category = this.route.snapshot.data.category;
    }
    

    有人知道为什么会这样吗?

    0 回复  |  直到 5 年前
        1
  •  3
  •   Eduardo Junior    5 年前

    首先需要修复路由定义。这可能就是问题所在。 尝试更改以下选项:

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

    致:

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

    因为解析需要是一个对象,而不是对解析程序的直接引用 here

    推荐文章