Home > Blockchain >  await for http request in angular
await for http request in angular

Time:01-07

I am having an issue turning this http request into a promise or something that I can wait for. I need to wait for the response because it contains the record id that was created with the request iself.

the function addChannelField is being called from ChannelFieldsService


addChannelField(data: any) {
   
    await this.http
      .post<{ message: string; post: any }>(
        BACKEND_URL,
        postData
      ).subscribe(responseData => {
        console.log('responseData', responseData);
        responseData // this is the data I want to return to function calling this function

      })

  }

the function is being called from another component using the following line:

  this.channelFieldsService.addChannelField(formData) 

I am tried adding async, await... that did not work. I think I am suppose to wrap this function in a promise but I cant get it to work

I found this exact question on stackoverflow but they dont show the answer, they only describe it. so i dont get it

CodePudding user response:

service.ts
public addChannelField(data: any): Observable<any> {
        return this.http.post<{ message: string; post: any }>(BACKEND_URL, postData);
}

component.ts
this.channelFieldsService.addChannelField(formData)
      .subscribe((response: any) => {
          console.log(response.id); // something like this
      });

Assuming you're using (Angular TypeScript RxJS).. The initial pseudocode would look like this. A service must just return an observable/promise and a component must subscribe to it. Kindly, consider making this code clean by applying best practices. Good luck!

CodePudding user response:

Try this:

addChannelField(data: any) {
    const data = await this.http
      .post<{ message: string; post: any }>(
        BACKEND_URL,
        postData
      ).toPromoise()

}

More about toPromose: https://www.learnrxjs.io/learn-rxjs/operators/utility/topromise

  • Related