Routing Angular Applications: Lesson 16 of 23

Data and Resolve

Up Next

About User Resolve

Autoplaying in 7 seconds!

Cancel

Resolve allows us to grab data before we activate a route and component.

This is a great way to make sure that content is ready for our components to use.

We'll create a new app/about/about-resolve.service.ts

Table of Contents

    import { Injectable } from '@angular/core';
    import { Resolve, ActivatedRouteSnapshot } from '@angular/router';
    import { User } from '../shared/models/user';
    import { UserService } from '../shared/services/user.service';
    
    @Injectable()
    export class AboutUsersResolve implements Resolve<User> {
    
      constructor(private service: UserService) {}
    
      resolve(route: ActivatedRouteSnapshot) {
        return this.service.getUsers().then(users => users);
      }
    
    }

    Once this is registered with the AboutModule, we can use it in our about.routing.ts:

    
    const aboutRoutes: Routes = [
      {
        path: '',
        component: AboutSectionComponent,
        children: [
          {
            path: '',
            component: AboutComponent,
            resolve: {
              users: AboutUsersResolve
            }
          },
          {
            path: ':username',
            component: AboutUserComponent
          }
        ]
      }
    ];```

    Chris Sevilleja

    173 posts

    Co-founder of Scotch.io. Slapping the keyboard until something good happens.