Home > database >  Capture Angular API response from service to component
Capture Angular API response from service to component

Time:11-16

In my Angular 12 application, I am making an API call in the service file and want to capture the response of the API in my component. But since the API response is async, the console below always returns undefined. I have tried async await as well. Here is what I have tried:

INSIDE SERVICE:

public checkEmail(emailToVerify: any) {
    this.myService.emailValidate({ email: emailToVerify }).subscribe({
      next: (data: { result: any) => {
        console.log('updateEmail-res', data);
        return data;
      },
      error: (err: any) => {
        console.log('updateEmail-err', err);
      }
    });
  }

INSIDE COMPONENT:

this.apiResponse = await this.myService.checkEmail(customerEmail);
 console.log("this.apiResponse", this.apiResponse)

CodePudding user response:

In Component

validateEmail = async () => {
    const params = {
      emailAddress: '[email protected]',
    };
    const apiResponse: boolean = await this.emailService.validateEmail(params);
    console.log(`apiResponse===`, apiResponse);
  };

In Service

export class EmailService {
  constructor() {}

  validateEmail = async (params: {
    emailAddress: string;
  }): Promise<boolean> => {
    return new Promise((resolve) => {
      const isValid = /^\w ([\.-]?\w )*@\w ([\.-]?\w )*(\.\w{2,3}) $/.test(
        params.emailAddress
      );

      resolve(isValid);
    });
  };
}

CodePudding user response:

The checkemail method does nothing. If you already have emailValidate, why put it in another method? just one emailValidate instead of checkEmail

this.apiResponse = await this.myService.emailValidate({ email: customerEmail});
 console.log("this.apiResponse", this.apiResponse)

o in you component:

this.myService.emailValidate({ email: customerEmail}).subscribe({
          next: (data: { result: any) => {
            console.log('updateEmail-res', data);
             this.apiResponse = data;
          },
          error: (err: any) => {
            console.log('updateEmail-err', err);
          }
        });
  • Related