Im working with angular 6 and I have the following Component
MainComponent.ts which have this code on ngOnInit:
ngOnInit() {
console.log('OnInit');
this.route.params.subscribe(params => {
if (params['id'] != null) {
this.id= params['id']
}
});
}
and then this on MainComponent.HTML
<DataComponent [id]="id"></DataComponent>
<TableComponent [id]="id"></TableComponent>
<FieldComponent [id]="id"></FieldComponent>
The route is: http://localhost:4200/Data/77
It all works perfectly until I need be clone or change the ID, so I need the MainComponent refresh all the IDs.. I did the following code:
this.router.navigate(['/Data', result.id_cloned_data]);
Edit: Routes
const appRoutes: Routes = [
{
path: 'Formula/:idFormula',
component: FormulaMainComponent,
pathMatch: 'full'
},
{ path: 'Formula', component: FormulaMainComponent, pathMatch: 'full' },
{ path: '', component: FormulaMainComponent, pathMatch: 'full' }
];
The URL changes to, for example: http://localhost:4200/Data/399 but the MainComponent dont refresh. I did an EventEmitter passing the new ID to the MainComponent but its still not working and I already tried on AppRoutes onSameUrlNavigation: 'reload'.
What am I doing wrong? Isnt it to reaload so each component Call its Get from API?
Variant 1:
public bookId$: Observable<string> // 'id' is bad name for variable, remember about code readability;
ngOnInit() {
this.bookId$ = this.activatedRoute.paramMap.pipe(
map((param) => {
return param.get('BOOK_ID');
}),
);
}
template of component:
<DataComponent [bookId]="bookId$ | async"></DataComponent>
<TableComponent [bookId]="bookId$| async"></TableComponent>
<FieldComponent [bookId]="bookId$ | async"></FieldComponent>.
Variant 2:
1) template of DataComponent:
<router-outlet></router-outlet>
2) example of router config:
{
children: [
{
component: DataChildComponent,
path: ':BOOK_ID',
},
],
component: DataComponent,
path: 'Data',
},
3) template of DataChildComponent:
<DataComponent [bookId]="bookId$ | async"></DataComponent>
<TableComponent [bookId]="bookId$| async"></TableComponent>
<FieldComponent [bookId]="bookId$ | async"></FieldComponent>
4) DataChildComponent:
public bookId$: Observable<string>;
ngOnInit() {
this.bookId$ = this.activatedRoute.paramMap.pipe(
map((param) => {
return param.get('BOOK_ID');
}),
);
}
Hope it helps!