Even though it seems like a common situation I haven't found a decent solution of how do I share a data from the parent to children routes.
Routes:
{
path: ':id',
component: DetailComponent,
children: [
{ path: 'overview', component: OverviewComponent },
{ path: 'profile', component: ProfileComponent }
]
}
Service:
@Injectable()
export class Service {
constructor(private http: Http) { }
getModel(id: number): Observable<Profile> {
// ajax request to the server using Http service
// returns Profile model
}
}
DetailComponent (parent):
@Component({
moduleId: module.id,
templateUrl: 'detail.component.html'
})
export class DetailComponent implements OnInit, OnDestroy {
model: any = {}; // how do I share this with children components avoiding another ajax request?
private paramSub: any;
private modelId: number;
constructor(
private activeRoute: ActivatedRoute,
private service: Service) { }
ngOnInit(): void {
this.paramSub = this.activeRoute.params.subscribe(params => {
this.modelId = +params['id'];
this.service.getModel(this.modelId).subscribe(model => this.model = model);
});
}
ngOnDestroy(): void {
this.paramSub.unsubscribe();
}
}
OverviewComponent (child):
@Component({
moduleId: module.id,
templateUrl: 'overview.component.html'
})
export class OverviewComponent implements OnInit, OnDestroy {
model: any = {};
private paramSub: any;
private modelId: number;
constructor(
private activeRoute: ActivatedRoute,
private service: Service) { }
ngOnInit(): void {
this.paramSub = this.activeRoute.parent.params.subscribe(params => {
this.modelId = +params['id'];
// another request to the server which I need to prevent
this.service.getModel(this.modelId).subscribe(model => this.model = model);
});
}
ngOnDestroy(): void {
this.paramSub.unsubscribe();
}
}
As you can see the parent component receives a common data that needs to be passed to the children routes. If possible to cache this data in the Service can someone advice a proper way of achieving this and invalidating the cache? If all of this is not a good practice please suggest the proper way.
angular: 2.0.0-rc.6; router: 3.0.0-rc.2