1

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

3 Answers 3

2

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!

Sign up to request clarification or add additional context in comments.

Comments

2

You can use RXJS firstValueFrom I'm using [email protected] reference: https://rxjs.dev/api/index/function/firstValueFrom

Import to use:

import { firstValueFrom } from 'rxjs';

Example usage:

async refreshUserData(): Promise<any> {
    return await firstValueFrom(this.http.get<any>(`${environment.apiUrl}/login/refreshdata`));
}

Comments

1

Try this:

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

}

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

NOTE: toPromise is deprecated since version 7.x of rxjs

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.