angularangular-resolver

Angular Resolver not working no provider for ()


I have this issue in a new project. I have created a route:

const routes: Routes = [
    {
        path: '',
        component: CategoriesComponent,
    },
    {
        path: ':categoryId',
        component: CategoryComponent,
        resolve: CategoryResolver,
    },
];

As you can see, it's trying to use a resolver, which looks like this:

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

When I use this code, I get an error:

Uncaught (in promise): NullInjectorError: R3InjectorError(CategoriesModule)[() => [ -> () => [ -> () => [ -> () => [ -> () => []: NullInjectorError: No provider for () => [!

If I comment out the resolver like this:

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

I no longer get the error, but obviously nothing is resolved. My code in my CategoryComponent just looks like this:

ngOnInit(): void {
    this.getCategory();
}

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

Does anyone know why this might be happening?


Solution

  • You first need to fix your routes definition. That may be the problem. Try to change the:

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

    to :

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

    Because the resolve needs to be an object and not the direct reference to the resolver as you can se here