Render JSON in html from Service [Ionic 4]

♀尐吖头ヾ 提交于 2020-04-17 22:09:41

问题


Thanks to parrycima, I created my first service.

results.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>

I can get object only in console mode, but not in HTML rendered.

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

With the same function I can rendering HTML fine in result.page.ts.


回答1:


From your service return 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();

 }


来源:https://stackoverflow.com/questions/60549888/render-json-in-html-from-service-ionic-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!