Reputation: 3
I am new to Angular. My app has three pages/components : header,sidebar and main-content which depends on sidebar list elements. Sidebar component render and list :
<a [routerLink]= "['/detail' , item.id]">{{item.placeName}}</a>
app.component.html
<app-nav></app-nav>
<br><br><br>
<div class="row">
<div class="col-3">
<app-place-list></app-place-list>
</div>
<div class="col-6">
<router-outlet></router-outlet>
</div>
</div>
and place-details component (is rendered and displayed )
place,id,comments are class variable
ngOnInit() {
this.activatedRoute.paramMap.subscribe(params => {
this.id=params.get('id');
});
this.doGet();
}
doGet(){
if(this.id){
this.service.getPlace(this.id).subscribe(res=>{
this.place=res;
this.comments=this.place.comments;
});
}
}
When clicked list elements works fine but once time. If clicked another elements no updated. I didnt understood. I have appropriate route path in app-routing.ts
{path:"detail/:id",component:PlaceDetailComponent}
Why didn't it update place-dettail.component.html in router-outler? Why does it works once ?
Upvotes: 0
Views: 1264
Reputation: 73367
You are only calling doGet()
once, so it will not be called again when route parameter is changed, I would also suggest to chain that request with the this.activatedRoute.paramMap
, for example using switchMap
or mergeMap
:
import { switchMap } from 'rxjs/operators';
// ...
ngOnInit() {
this.activatedRoute.paramMap.pipe(
switchMap((params) => this.service.getPlace(params.get('id')))
).subscribe(res => {
this.place = res;
this.comments = res.comments;
});
}
Upvotes: 1
Reputation: 194
You have to call the doGet
method in the observable subscription:
ngOnInit() {
this.activatedRoute.paramMap.subscribe(params => {
this.id=params.get('id');
this.doGet();
});
}
...
This happens because your component is already loaded so this dont call the ngOnInit
again. on the other hand if your component was destroy and loaded again then this call this this method again.
Upvotes: 2