I have two components: recipe and recipe-detail. Recipe is displaying list of recipes from my database and recipe-detail should display details of given recipe. What I want to achieve is to whenever someone click on recipe name I want to route him to recipe-detail component. This is my recipe html:
<section class="columns">
<div class="column" *ngFor="let recipe of RecipeList">
<h2><a routerLink="recipes/{{recipe.Id}}" routerLinkActive="true">{{recipe.name}}</a></h2>
<p>{{recipe.recipeBody}}</p>
</div>
</section>
My routing file:
{path:'recipes', component: RecipeComponent},
{path: 'recipes/:id', component: RecipeDetailsComponent}
And my recipe-detail ts:
export class RecipeDetailsComponent implements OnInit {
@Input() recipe! : any;
constructor(private route: ActivatedRoute,
private sharedService: SharedService) { }
ngOnInit(): void {
this.getRecipe();
}
getRecipe() : void{
const id = Number(this.route.snapshot.paramMap.get('id'));
this.sharedService.getRecipeById(id).subscribe(recipe => this.recipe == recipe);
}
}
Simple html for test:
<h2>Name : {{recipe.name}}</h2>
<h2>RecipeBody: {{recipe.recipeBody}}</h2>
<h2>IntendedUse: {{recipe.IntendedUse}}</h2>
<h2>CoffeeId: {{recipe.coffeeId}}</h2>
Results: When I click on recipe name (recipe.component) it redirects me to: http://localhost:4200/recipes/recipes when it sould be for example http://localhost:4200/recipes/1
And in the console i get: TypeError: Cannot read properties of undefined (reading 'name')
Edit: How i fetch it:
getRecipes() : Observable<any[]> {
return this.http.get<any>(this.ApiUrl '/Recipes')
}
getRecipeById(val:any){
return this.http.get<any>(this.ApiUrl '/Recipes/', val);
}
CodePudding user response:
You need to use = to assign the values but not ==.
From:
this.sharedService.getRecipeById(id).subscribe(recipe => this.recipe == recipe);
To:
this.sharedService.getRecipeById(id).subscribe((recipe:any) => this.recipe = recipe);
CodePudding user response:
I would recommend doing it as below by subscribing
import { ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute,private sharedService: SharedService) {
ngOnInit() {
this.route.params
.subscribe(
(params: Params) => {
this.sharedService.getRecipeById(params['id']).subscribe(recipe => {
this.recipe = recipe;
})
}
);
}
}
or even make it better with switchMap