首页 > 解决方案 > 从服务 [Ionic 4] 在 html 中呈现 JSON

问题描述

感谢 parrycima,我创建了我的第一个服务。

结果.service.ts

  constructor(private httpService: HttpClient) {

  }

  async checkFunc() {

    this.apiurl = 'https://my.apiurl.com/';

    this.httpService.get(this.apiurl).subscribe(res => {

         if (res) {
          this.items = Object.keys(res).map(function(key) {
           return res[key];
          });
         }

        }, (err: HttpErrorResponse) => {
         console.log (err.message);
        }
      );

  }

app.component.ts

export class AppComponent {

    constructor(
        public myService: ResultsService,
        private httpService: HttpClient
      ) {

       this.myService.checkFunc();

    }

app.component.html

<ion-content>
  <ion-list *ngFor="let item of items">
    <ion-item>{{item.operator}} 
      <div class="icon-status" slot="end">
        <ion-icon name="{{item.status}}"></ion-icon>
      </div>
  </ion-item>
</ion-list>
</ion-content>

我只能在控制台模式下获取对象,但不能在呈现的 HTML 中。

https://i.stack.imgur.com/yD3mA.jpg

使用相同的功能,我可以在 result.page.ts 中很好地呈现 HTML。

标签: ionic-frameworkionic4

解决方案


从您的服务返回 this.items

async checkFunc() {

this.apiurl = 'https://my.apiurl.com/';

await this.httpService.get(this.apiurl).subscribe(res => {

     if (res) {
      this.items = Object.keys(res).map(function(key) {
       return res[key];
      });
      return this.items
     }

    }, (err: HttpErrorResponse) => {
     console.log (err.message);
    }
  );

}


export class AppComponent {
   items;
    constructor(
      public myService: ResultsService,
      private httpService: HttpClient
     ) {

   this.items = this.myService.checkFunc();

 }

推荐阅读