Reputation: 1221
I have implemented the following code to redirect to my Greenhouse Plants
<div *ngFor="let plant of plants" (click)="openPlant(plant)">
<div class="row">
<div class="col-md-3 p-l-0 p-r-0 my-auto">
<img src="..." class="navbar-item-icon">
</div>
<div class="col-md-9 my-auto">
{{plant.englishName}}
</div>
</div>
</div>
(click) openPlant:
public openPlant(plant: PlantModel) {
var foundPoor = this.checkIfPlantIsPoor(plant),
this._generalService.openPlant(foundPoor, plant)
}
_generalService openPlant:
public openPlant(foundPoor, plant: PlantModel) {
if (foundPoor) {
...
} else {
this.router.navigate(['desktop/plant/' + plant.id]);
}
}
So, when I click to a plant, it will redirect just fine. But after it redirects to the first plant, when i click to others, the url in the browser is changing but it wont redirect to the actual route! It is just sstaying to the first plant I clicked.
So the first time it goes to http://localhost:4200/desktop/plant/2, then I click to redirect to http://localhost:4200/desktop/crop/11, the url in the browser changes to http://localhost:4200/desktop/crop/11 but the UI stays on http://localhost:4200/desktop/plant/2
Here is my app.routing
const routes: Routes = [
...
{ path: 'desktop', loadChildren: () => import('./pages/desktop/desktop.module').then(m => m.DesktopModule) },
...
];
Here is desktop.routing:
const routes: Routes = [
...
{ path: 'plant/:id', component: PlantComponent},
...
];
Here is PlantComponent:
HTML
<div class="container">
<plant-item [plantID]=plantID></crop>
</div>
TS
ngOnInit() {
console.log(this.plantID)
var _this = this
var route = this.router.url
this.plantID = this.activated_route.snapshot.paramMap.get("id")
}
Here is PlantItemComponent TS:
...
this._plantService.currentPlants.subscribe(res => {
this.activeSeed = this._plantsService.getMyActiveSeed(res, this.plantID)
...
})
on ngOnInit it will console.log only the first time i navigate to the first Plant. When I click to navigate to ther others it wont console.log.
Here is a stackblitz focusing on the routing and how i call needed components: https://stackblitz.com/edit/angular-c9g1hl
Upvotes: 0
Views: 386
Reputation: 2710
Problem here is that when you navigate to the same route, even with a different param, Angular reutilizes the component instance. That means that your ngOnInit
function is getting called only once. I think the simplest way of solving this is handling ActivatedRoute
as an observable:
ngOnInit() {
console.log(this.plantID)
var _this = this
var route = this.router.url
this.activated_route.params.subscribe(params => {
this.plantID = params.id;
});
}
Upvotes: 1