I am writing some post and get requests to access an API in Angular. In my post request, I create a new item and get an id for that item. To then write a get request to get that item, i need to append the item id to the url.
How can I access the id from the post request in the get request?
I have created the variable id
that gets overwritten in createItem()
and can be accessed in HTML by simply writing {{id}}
. But I am not able to access the overwritten content from createItem()
inside of getItem()
; the variable id
remains empty.
My code so far:
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;
});
}