What Is Route Resolver, Why Use and How to Implement

Source: Internet
Author: User
Keywords route resolver route resolver example what is a route resolver route resolver tutorial

One way for handling retrieving and displaying data from an API is to route a user to a component, and then in that component’s ngOnInit hook call a method in a service to get the necessary data. While getting the data, perhaps the component can show a loading indicator.

 

There is another way to use what is known as a route resolver, which allows you to get data before navigating to the new route.

 

What is Route Resolver?

Router Resolver is actually a service. When jumping to a certain route, the service can get the current ActivatedRoute and get the data it carries. Here you can go to the server to get some data in advance, or do some data conversion before proceeding to the component. Instantiation and rendering. For example, when the user is about to jump to the feedback page of the application to fill in the feedback, we can check whether it is a logged-in user through a membership-resolver, if not, then jump to the login page, if yes, display the historical feedback and feedback filling form Entrance.

 

Why Use Route Resolvers?

Let's think about the scenario when your logic relies on the length of an array, which is manipulated when an API call is completed. For example, you may want to display in a component the items of this array which were just fetched in an unordered list.

 

In this situation, you might get into a problem because your data will come up after the component is ready. Items in the array do not really exist yet. Here, the Route Resolver comes in handy. It will fetch your data before the component is ready. Your conditional statements will work smoothly with the Resolver.

 

Implementing a Route Resolver

After we have finished with the basics explanation on why and how to use a route resolver, let’s start implementing one. In this short example, I will demonstrate only the mandatory code.

First of all, we will need a service that will fetch the user data for us. In this service, we have a function called getUsers() that returns an observable.

@Injectable({

providedIn: 'root'

})

export class FakeApiService {

  constructor(private http: HttpClient) { }

  private usersEndpoint = "https://jsonplaceholder.typicode.com/users";

  getUsers(): Observable<any> {

    // We do not subscribe here! We let the resolver take care of that...

    return this.http.get(this.usersEndpoint);

  }

}

 

It is important no to subscribe to the function getUsers. The route resolver called UserResolver will take care of this for you. The next step is to create a new service called UserResolver which will implement the resolve function of the Resolve interface of the router.

@Injectable({

providedIn: 'root'

})

export class UserResolverService implements Resolve<any> {

  constructor(private fakeApi: FakeApiService) { }

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

    return this.fakeApi.getUsers().pipe(

      catchError((error) => {

      return empty();

      });

    );

  }

}

 

This service, UserResolver, will subscribe automatically to the getUsers observable and provide the router with the fetched data. In case of an error, while fetching the data, you can send an empty observable and the router will not proceed to the route.

 

The navigation will be terminated at this point. This last step is to create a component that will be called when the user goes to the /users route. Typically, without a Resolver, you will need to fetch the data on the ngOnInit hook of the component and handle the errors caused by ‘no data’ exists. The user's component is a simple one. It just gets the user's data from the ActivatedRoute and displays them into an unordered list.

 

After you have created the user's component, you need need to define the routes and tell the router to use a resolver ( UserResolver). This could be achieved with the following code into the  app-routing.modulte.ts.

const routes: Routes = [

{ path: 'users', component: UsersComponent, resolve: { users: UserResolverService } }

];

 

@NgModule({

  imports: [

  CommonModule,

  FormsModule,

  HttpClientModule,

  RouterModule.forRoot(routes)],

  exports: [RouterModule]

})

export class AppRoutingModule { }

 

You need to set the resolve property into the user's route and declare the UserResolver. The data will be passed into an object with a property called users. After that, you are almost done. There is only one thing you need to do. You must get the fetched data into the users' component via the ActivatedRoute with the following code.

 

constructor(private activatedRoute: ActivatedRoute) { }

 

users: any[];

 

ngOnInit() {

  this.activatedRoute.data.subscribe((data: { users: any }) => {

  this.users = data.users;

  });

}

 

Then, you can just display them into HTML without any *ngIf statements ( *ngIf=”users && users.length > 0 ) because the data will be there before the component is loaded.

 

<h2>Fetched Users:</h2>

<ul>

<li *ngFor="let user of users">{{ user.name }}</li>

</ul>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.