Last active
June 11, 2019 07:49
-
-
Save mccabiles/fffe2171ba537d86e2493836d1607a0a to your computer and use it in GitHub Desktop.
Use a Resolver to asynchronous pre-fetch data before navigating to Angular component,
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component } from '@angular/core'; | |
import { ActivatedRoute } from '@angular/router'; | |
@Component({ | |
template: '<div> {{ ourData }} </div>' | |
}) | |
export class DetailsComponent { | |
ourData = ''; | |
constructor(private route: ActivatedRoute) { } | |
ngOnInit() { | |
this.getData(); | |
} | |
getData() { | |
// We have access to the resolve object we passed in our Routes. | |
// update the ourData prop whenever route.data changes: | |
this.route.data.subscribe(({ ourData }) => this.ourData = ourData ); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from "@angular/core"; | |
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; | |
class Backend { | |
getData() { return data; } | |
} | |
@Injectable() | |
export class Resolver implements Resolve<any> { | |
constructor (private backend: Backend) {} | |
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<any> { | |
// assuming our route path is '/data/:id', we can access the 'id' parameter: | |
return this.backend.getData(route.params.id); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { NgModule } from '@angular/core'; | |
import { Routes, RouterModule } from '@angular/router'; | |
import { DetailsComponent } from './details.component'; | |
import { Resolver } from './Resolver'; | |
const routes: Routes = [ | |
{ | |
path: '/data/:id', | |
component: DetailsComponent, | |
resolve: { ourData: Resolver }, | |
} | |
]; | |
@NgModule({ | |
declarations: [ | |
DetailsComponent | |
], | |
imports: [ | |
// use .forChild(routes) if routing module is not root | |
RouterModule.forRoot(routes), | |
], | |
exports: [ | |
RouterModule, | |
], | |
providers: [ | |
// Provide the Resolver injectable: | |
Resolver, | |
] | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment