Tengo dos componentes: receta y receta-detalle. La receta muestra una lista de recetas de mi base de datos y el detalle de la receta debe mostrar los detalles de la receta dada. Lo que quiero lograr es que cada vez que alguien haga clic en el nombre de la receta, quiero enrutarlo al componente de detalles de la receta. Esta es mi receta 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>Mi archivo de enrutamiento:
{path:'recipes', component: RecipeComponent}, {path: 'recipes/:id', component: RecipeDetailsComponent}Y mi receta-detalle 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); } }HTML simple para la prueba:
<h2>Name : {{recipe.name}}</h2> <h2>RecipeBody: {{recipe.recipeBody}}</h2> <h2>IntendedUse: {{recipe.IntendedUse}}</h2> <h2>CoffeeId: {{recipe.coffeeId}}</h2>Resultados: cuando hago clic en el nombre de la receta (recipe.component) me redirige a: http://localhost:4200/recipes/recipes cuando debería ser, por ejemplo, http://localhost:4200/recipes/1
Y en la consola obtengo: TypeError: No se pueden leer las propiedades de undefined (leyendo 'nombre')
Editar: Cómo lo busco:
getRecipes() : Observable<any[]> { return this.http.get<any>(this.ApiUrl + '/Recipes') } getRecipeById(val:any){ return this.http.get<any>(this.ApiUrl + '/Recipes/', val); }Recomendaría hacerlo de la siguiente manera suscribiéndose
HTML
<h2><a [routerLink]="['/recipes', recipe.Id]" routerLinkActive="true">{{recipe.name}}</a></h2> 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; }) } ); } }o incluso mejorarlo con switchMap
Necesita usar = para asignar los valores pero no ==.
De:
this.sharedService.getRecipeById(id).subscribe(recipe => this.recipe == recipe);A:
this.sharedService.getRecipeById(id).subscribe((recipe:any) => this.recipe = recipe);