首页 > 解决方案 > 如何在 Angular 承诺中获得 javascript 响应

问题描述

我在角度组件中调用 javascript 函数。我将 JS 文件包含在“angular.json”中,它工作正常。JS 函数执行 http GET 请求并返回数据。问题是我不能告诉 Angular 等待 JS 响应然后获取数据。

这是我的 JS 函数:

function getDataJsFunct(id) {
   var params = {id:id}
   apiClient.getById(params) { console.log('data from JS', result); 
      return result;
   }
}

这是我的 TS 文件:在 api-services.ts

declare var getDataJsFunct: any;

export class ApiServices {
.
.
   public getAction(id) {
    return new Promise ( resolve => {
      const data = getDataJsFunct(id);
      if (data) {
        console.log('result', data);
        return resolve();
      }

    });
  }
}

在 component.service.ts

@Injectable()
export class ComponentService {
  constructor(private serviceProvider: ApiServices) {}
  getDataFromProvider(id) {
    return this.serviceProvider.getAction(id);
  }
}

在组件.ts

  ngOnInit() {
  let id = '123456';
  this.componentService.getDataFromProvider(id).then((data: any) => {
     this.dataFromBd = data.Items[0];
  },
  error => {
     console.log('Error in getting Data', error);
  });
}

该程序在“ getDataFromProvider(id) 处崩溃。***then***((data ”,因为 getDataFromProvided(id) 未定义。我想我需要一个承诺来告诉 Angular 等待 JS 响应然后继续执行。请问我应该如何以及在哪里这样做?

标签: javascriptangular

解决方案


我认为您的问题是您没有在服务中传递正确的变量名。

目前,您有:

@Injectable()
export class ComponentService {
  constructor(private serviceProvider: ApiServices) {}
  getDataFromProvider(urlApi) {
    return this.serviceProvider.getAction(id);
  }
}

当函数的参数为​​ 时,您正在this.serviceProvider.getAction(id)使用变量调用。idurlApi

你应该urlApi改变id

@Injectable()
export class ComponentService {
  constructor(private serviceProvider: ApiServices) {}
  getDataFromProvider(id) {
    return this.serviceProvider.getAction(id);
  }
}

你能检查一下是不是这个问题吗?


推荐阅读