Skip to content

Instantly share code, notes, and snippets.

@tomastrajan
Last active September 16, 2019 04:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomastrajan/07b61ab9baf2e8e4f33e67fb8a720919 to your computer and use it in GitHub Desktop.
Save tomastrajan/07b61ab9baf2e8e4f33e67fb8a720919 to your computer and use it in GitHub Desktop.
Angular Model Pattern - initialize model on route change
/* route configuration */
const routes: Routes = [
{
path: 'todos',
component: TodosComponent,
resolve: {
todosInitialized: TodosService
}
}
/* ... */
];
/* business service */
@Injectable()
export class TodosService implements Resolve<boolean> {
resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> {
// get data from http, websocket, localstorage, ...
// retrieve url state from route (query params, path params, ...)
// sync
const data = storage.get('my-data');
this.model.set(data); // set data in model
return Observable.of(true); // to finish navigation to the new route
// or async
return this.http.get(url)
.map(res => res.json()) // extract data from response
.do(data => this.model.set(data)) // set data in model
.mapTo(true); // return true if successful
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment