Estoy escribiendo una publicación y recibo solicitudes para acceder a una API en Angular. En mi solicitud de publicación, creo un nuevo elemento y obtengo una identificación para ese elemento. Para luego escribir una solicitud de obtención para obtener ese artículo, necesito agregar la identificación del artículo a la URL.
¿Cómo puedo acceder a la identificación de la solicitud de publicación en la solicitud de obtención?
Creé la id
de la variable que se sobrescribe en createItem()
y se puede acceder en HTML simplemente escribiendo {{id}}
. Pero no puedo acceder al contenido sobrescrito de createItem()
dentro de getItem()
; la id
de la variable permanece vacía.
Mi código hasta ahora:
import { HttpClient } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; import { HttpHeaders } from '@angular/common/http'; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded', Authorization: '...', }), }; type CreatedItem = {id: string; inventory: []} @Component({ selector: 'home-component', templateUrl: './home.component.html', styleUrls: ['./home.component.scss'], }) export class HomeComponent { url = 'url here'; id=""; constructor(private httpClient: HttpClient) {} ngOnInit(): void { this.createItem(); this.getItem(); } createItem() { this.httpClient.post(this.url, null, httpOptions).subscribe((res) => { const data = res; this.id = (data as CreatedItem).id; }); } getItem() { this.httpClient .get<any>( this.url + this.id, httpOptions ) .subscribe((res) => { const data = res; }); }
La suscripción de getItem() no tiene idea de si la suscripción de createItem() se ha completado o no, lo que dará como resultado que la identificación sea nula cuando se active getItem(). La solución fea sería solo llamar a getItem() una vez que la suscripción de createItem() esté completa y haya una identificación:
ngOnInit(): void { this.createItem(); } createItem() { this.httpClient.post(this.url, null, httpOptions).subscribe((res) => { const data = res; this.id = (data as CreatedItem).id; this.getItem(this.id) }); } getItem(id: string) { this.httpClient .get<any>( this.url + id, httpOptions ) .subscribe((res) => { const data = res; }); }
Una mejor manera de hacer esto sería usar un mapa de interruptores rxjs