Home > Net >  Access variable from another function Angular - Get & Post [duplicate]
Access variable from another function Angular - Get & Post [duplicate]

Time:10-05

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

CodePudding user response:

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

  • Related