-2

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;
      });
  }
janesbeat
  • 3
  • 2
  • There's nothing in your code to ensure the creation has completed before you try to get the item. Expose the observables from the methods rather than just subscribing to them locally, otherwise the data you're fetching isn't actually usable anywhere else. – jonrsharpe Oct 03 '21 at 08:18
  • Sorry, could you explain this a bit further? I don't really have experience in Angular and can't really find anything about this. – janesbeat Oct 03 '21 at 13:44
  • It's not really an Angular- or even RxJS-specific problem, read e.g. https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call. – jonrsharpe Oct 03 '21 at 13:54

1 Answers1

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

SP de Wit
  • 215
  • 1
  • 9