a site for tech enthusiast

Angular resolver is a very nice way to improve user-experience when browsing between pages in our app. By implementing resolver, it is possible for us to load all data from remote server before our route actually activated and component being rendered into the browser.

Before we begin let’s take a look into the scenario bellow:

“We want to show a list of movie in our application where the data is served from remote server at https://facebook.github.io/react-native/movies.json, not all the information will be rendered, only movie title, and in order to give the best experience to our user’s we won’t display anything until the data is fetched successfully”.

Now we took our first step, define the application route:

1

2

3

4

5

6

7

constappRoutes:Routes=[

{path:'',component:AppComponent},

{

path:'movies',

component:MoviesComponent

}

]

From the route above we know that we should have two components (AppComponent and MoviesComponent) in our app, AppComponent will be bootstrap component and it only render router-outlet:

app.component.ts

JavaScript

1

2

3

4

5

6

7

import{Component}from'@angular/core';

@Component({

selector:'app-root',

template:'<router-outlet></router-outlet>'

})

exportclassAppComponent{}

Now let’s create MoviesComponent:

movies.component.ts

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

import{Component,OnInit}from'@angular/core';

import{ActivatedRoute}from'@angular/router';

@Component({

selector:'app-movies',

template:`

<p>Movie list</p>

<ul>

<li *ngFor="let movie of movies.movies">{{movie.title}}</li>

</ul>

`

})

exportclassMoviesComponentimplementsOnInit{

publicmovies:any;

constructor(privateroute:ActivatedRoute){}

ngOnInit(){

this.movies=this.route.snapshot.data['movies'];

}

}

Our movie list will be displayed inside MovieComponent and the data stored from current activated route snapshot. Next step, create a service that fetch data from remote server, this service must implement Resolve interface and can return either Observable or Promise object: