Last active
September 16, 2019 04:58
-
-
Save tomastrajan/07b61ab9baf2e8e4f33e67fb8a720919 to your computer and use it in GitHub Desktop.
Angular Model Pattern - initialize model on route change
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
/* 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