首页 > 解决方案 > HTML页面上的http API请求Angular 12为空

问题描述

我在尝试调用 API 时有点困惑。我首先创建了一个调用 API 的服务:

public getCategories(): Observable<any> {
  let getCategoriesUrl = 'http://localhost:4300/WS/GetCategories';
  return this.http.get<any>(getCategoriesUrl, {
    headers: this.httpOptions, responseType: 'text' as 'json'
  });
}

在我的组件中,我有一个检索数据的方法。我的数据不干净,这就是为什么要清理返回的特殊字符。这也是为什么在我的服务中我不检索特定模型的可观察对象,而是“任何”。这是实现。

private getCategories() {
  this.soapService.getCategories().subscribe(
    (res) => {
      console.log(typeof res);
      res = res.replace(/\n/g, '');
      this.replacement.forEach(
        item => {
          res = res.replace(item, '');
        }
      );
      // res is a string with all data from API call => parsing string to object
      // console.log(res);
      this.categoriesResponseModel = JSON.parse(res);
      console.log('iterate after string parsing');
      // @ts-ignore
      for (const category of this.categoriesResponseModel.CATEGORIES) {
        // console.log(category);
        this.categories.push(category);
      }
      console.log("In get categories");
      console.log("Output  ", this.categories);
    },
    (err) => {
      console.log(err.message);
    },
    () => {
      console.log('Completed - Categories pushed');
    }
  );
}

在方法中,输出在包含以下 console.log 的行上打印了预期值: console.log("Output ", this.categories);

在此处输入图像描述

ngOnInit() {
  console.log('# ngOnInit() called');
  this.getCategories();
  console.log(this.categories)
  console.log("output  " + this.categories)
}

在 ngOnInit 中,我确实有一个空数组作为输出。我测试在 HTML 页面中显示结果:

{{ categories.length }}
<div *ngFor="let category of categories">
  {{ category.CategoryID }} - {{ category.CategoryName }}: {{ category.DocDescription }}
</div>

不幸的是,我得到长度等于 0。

标签: angularapi

解决方案


我受到 Octavian Mărculescu 建议使用 ChangeDetectorRef 的启发。这是组件中 getCategories 的更新代码。

我还更改了调用 getCategories 的位置并将其放在构造函数中

constructor(@Inject(TRANSLATION) public readonly lang: Translation,
            private cd: ChangeDetectorRef,
            private soapService: SoapApiService,
            private route: ActivatedRoute) {
  this.getCategories();
}

这是实现:

getCategories(): void {
  const values: CategoryModel[] = [];
  const response = this.soapService.getCategories().subscribe(
    (res) => {
      console.log(typeof res);
      res = res.replace(/\n/g, '');
      this.replacement.forEach(
        item => {
          res = res.replace(item, '');
        }
      );
      // res is a string with all data from API call => parsing string to object
      // console.log(res);
      this.categoriesResponseModel = JSON.parse(res);
      console.log('iterate after string parsing');
      // @ts-ignore
      for (const category of this.categoriesResponseModel.CATEGORIES) {
        // console.log(category);
        values.push(category);
      }
      this.cd.markForCheck();
    },
    (err) => {
      console.log(err.message);
    },
    () => {
      console.log('Completed - Categories pushed');
      this.categories = values;
      console.log(this.categories);
    }
  );
}

推荐阅读