Search code examples
angularangular-router

How to resolve some json with the angular router


I'm trying to resolve some data directly in the router, like this

export const routes: Routes = [
    {
        path: 'users/:userId',
        component: UserComponent,
        resolve: {
            profile: { name: 'John Doe', .... }
        }
    }
];

DEMO

So, when I navigate to this route I get the following error

ERROR Error: Uncaught (in promise): Error: No provider for John Doe!

The question I have, is how can I resolve static json


Solution

  • Change resolve to data:

    export const routes: Routes = [
        {
            path: 'users/:userId',
            component: UserComponent,
            data: {
                profile: { name: 'John Doe', .... }
            }
        }
    ];
    

    Access that data via the route snapshot:

    this.route.snapshot.data['profile'];
    

    where this.route is the activated route service that is injected into the component you are working in.

    export class UserComponent {
      constructor(private route: ActivatedRoute) { }
    }