Home > front end >  Angular TypeScript: waiting for a void method to run before another method
Angular TypeScript: waiting for a void method to run before another method

Time:02-10

I have a method in an Angular component that pulls data via HttpClient subscription, and assigns it to an attributes this.allData, then instantiates an empty dictionary of parameters based on this, to pass to a second function:

export class TestComponent implements OnInit {

  allData: object[] = []
  activeData: object = {}

  constructor(private http: HttpClient) { }

  ngOnInit(): void {
    this.getData()
    this.makeRequestBasedOnData()
  }

  getData() {
    this.http.get(this.url).subscribe(res => {
      for (let datum of res["data"]) {
        this.allData.push({
          "key": Object.keys(datum)[0],
          "values": Object.values(datum)[0]
        })
        this.activeData[Object.keys(datum)[0]] = ""
      }
    })
  }

  makeRequestBasedOnData() {
    let testParams = this.activeData
    console.log(testParam)
  }

}

I need these steps to happen sequentially. At the moment, logging the testParams in makeRequestBasedOnData() simply shows an empty object {}. When I try to return arbitrarily in the first method, I get a TypeScript error that you cannot assign a promise to type void.

How do I enforce synchronicity here even though neither method actually returns anything?

CodePudding user response:

You can return Observable from getData method and proceed with any other methods within subscribe:

ngOnInit(): void {
  this.getData().subscribe(() => this.makeRequestBasedOnData());
}

getData() {
  return this.http.get(this.url).pipe(
    tap(res => {
      // update allData
    })
  );
}

where:

  • pipe method allows us to provide any kind of transformation with the data returned from http.get(...) call.

  • tap is a rxjs operator for side-effects, meaning that we can do everything we want with the response without modifying Observable flow.

  •  Tags:  
  • Related