typescript 捕获从服务到组件的Angular API响应

hpcdzsge  于 2022-11-18  发布在  TypeScript
关注(0)|答案(2)|浏览(100)

在我的Angular 12应用程序中,我在服务文件中调用了一个API,并希望在我的组件中捕获API的响应。但是由于API响应是异步的,下面的控制台总是返回undefined。我也尝试过异步等待。下面是我所尝试的:
内部服务:

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);
      }
    });
  }

内部组件:

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

ffscu2ro1#

在组件中

validateEmail = async () => {
    const params = {
      emailAddress: 'test@gmail.com',
    };
    const apiResponse: boolean = await this.emailService.validateEmail(params);
    console.log(`apiResponse===`, apiResponse);
  };

使用中

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);
    });
  };
}
raogr8fs

raogr8fs2#

checkemail方法什么也不做。如果你已经有了emailValidate,为什么要把它放在另一个方法中呢?

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

o在您的组件中:

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);
          }
        });

相关问题