【问题标题】:Render JSON in html from Service [Ionic 4]从服务 [Ionic 4] 在 html 中呈现 JSON
【发布时间】:2020-03-06 01:12:55
【问题描述】:

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

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>

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

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

使用相同的功能,我可以在 result.page.ts 中渲染 HTML。

【问题讨论】:

    标签: ionic-framework ionic4


    【解决方案1】:

    从您的服务返回 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();
    
     }
    

    【讨论】:

    • 感谢您的帮助。出现此错误:AppComponent.html:4 错误错误:找不到类型为“object”的不同支持对象“[object Promise]”。 NgFor 只支持绑定到 Arrays 等 Iterables。
    猜你喜欢
    • 1970-01-01
    • 2019-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-03
    • 2019-03-05
    • 1970-01-01
    • 2020-07-02
    相关资源
    最近更新 更多