Routing Angular Applications: Lesson 17 of 23

About User Resolve

Up Next

Dashboard Section

Autoplaying in 7 seconds!

Cancel

Important Note: There may be an error:

TypeScript Error: Class AboutUserResolve incorrectly implements the interface

Change Resolve<User> to Resolve<User[]> to fix. TypeScript wants the possibility of an array of users to come back.

Notes

Just like we created a resolve for our AboutComponent, we'll create the same thing for our AboutUserComponent.

Table of Contents

    about-user-resolve.service.ts

    import { Injectable } from '@angular/core';
    import { Router, Resolve, ActivatedRouteSnapshot } from '@angular/router';
    import { User } from '../shared/models/user';
    import { UserService } from '../shared/services/user.service';
    
    @Injectable()
    export class AboutUserResolve implements Resolve<User> {
    
      constructor(private service: UserService, private router: Router) {}
    
      resolve(route: ActivatedRouteSnapshot) {
        let username = route.params['username'];
    
        return this.service.getUser(username).then(user => {
          if (user) {
            return user;
          } else {
            // navigate the user back to the about page
            this.router.navigate(['/about']);
            return false;
          }
        });
      }
    
    }

    Chris Sevilleja

    176 posts

    Founder of Scotch.io. Google Developer Expert in Web Technologies. Slapping the keyboard until something good happens.