Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

174
Vistas
Access variable from another function Angular - Get & Post

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;
      });
  }
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

getItem()'s subscription has no idea whether or not createItem()'s subscription has completed or not which will result in the id being null when getItem() fires. The ugly fix would be to only call getItem() once createItem()'s subscription is complete and there is an id:

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;
            });
    }

A better way to do this would be to use a rxjs switchmap

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda