【问题标题】:HTTP Get request single object Ionic 2HTTP 获取请求单个对象 Ionic 2
【发布时间】:2017-06-29 22:04:00
【问题描述】:

我正在使用 API 来提取数据,然后将其打印到页面上,我已经成功地让它适用于超过 1 个对象的 json 响应,因为它解析了“匹配”层次结构。如果我为一个对象执行此操作,我似乎无法将其打印出来。

我已经在工作并且可以打印出来的 Json 是

和有效的代码

<ion-content>
    <ion-list>
        <ion-item *ngFor="let item of api" [navPush] = "detailsPage" detail-push>
            <div class="thumb">
                <img src="{{item.smallImageUrls}}">
            </div>
            <div class="text">
                <div class="title">
                    <h1>{{item.recipeName}}</h1>
                </div>
                <div class="rating">
                    <rating [(ngModel)]="item.rating"></rating>
                </div>
                <div class="time">
                    <p>{{item.totalTimeInSeconds | HoursMinutesSeconds}} minutes</p>
                </div>
                <div class="ingredients">
                    <p>{{item.ingredients.length}} Ingredients</p>
                </div>

                <div class="course">
                    <p>{{item.attributes.course}} </p>
                </div>

            </div>
        </ion-item>
    </ion-list>
</ion-content>

打字稿

    this.http.get('http://api.yummly.com/v1/api/recipes?_app_id=397aed16&_app_key=69e2565adcec7a6609b18bef31261e62')
      .map(res => res.json())
      .subscribe(data => {
        // we've got back the raw data, now generate the core schedule data
        // and save the data for later reference
        console.log(data);
        this.listing = data.matches;
        resolve(this.listing);
      });

Json 被卡住了

我的要求是

this.http.get('mylink.co.uk')
  .map(res => res.json())
  .subscribe(data => {
    console.log(data);
    this.details = data;
    resolve(this.details);
  });

角度为{{attribution}}

如果有人能指出我哪里出错了,那就太好了

【问题讨论】:

  • 所以你告诉你要打印 this.details.attribution 。在模板中填写此作品?
  • @RahulSingh 是的,我想打印出其中的任何一个项目,但它只会给我留下一个空的 html 元素
  • 你可以这样试试 this.details[0].attribution
  • @RahulSingh 这引发了一个错误,我已经用当前有效的代码更新了我的问题,并且已经打印出了对象,以便更清楚我的目标。
  • 那么你有一个解决方案吗?很棒

标签: arrays json angular object typescript


【解决方案1】:

按照这个例子我会解决你的问题,我跟着我解决了我的问题。

见:

https://angular.io/guide/http

https://google.github.io/styleguide/jsoncstyleguide.xml

models.ts:

export interface Location {
  id?: string;
  name?: string;
  author?: { 
    id?: string, 
    name?: string, 
    followerCount?: string
  }
}

模拟位置.service.ts:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

import { Observable } from 'rxjs/Observable';

import { Location } from '@core/models';

@Injectable()
export class MockLocationsService  {

  private readonly URL = 'assets/data/locations.json';

  constructor(protected httpClient: HttpClient) {}

  public list(): Observable<Location[]>   {
    return this.httpClient.get<Location[]>(this.URL);
  }

}

my.page.ts:

  import { Location } from '@core/models';
    
    ...
    
    export class MyPage implements OnInit, OnDestroy {
    
      public items: Array<Location> = [];
      private itemsSubscription: Subscription;
    
      constructor(public navCtrl: NavController,
                  public navParams: NavParams,
                  private locationsService: MockLocationsService,
                  private logger: LoggerService) {
    
      }
      ...
    
      public ngOnInit() {
    
        this.itemsSubscription = this.locationsService.list().subscribe(data => {
          this.items = data;
        });
      }
    
      ...
    
      public ngOnDestroy() {
        this.itemsSubscription.unsubscribe();
      }
    
    }

参考:https://forum.ionicframework.com/t/how-to-map-api-objects-in-ionic-in-a-good-way/140249/2

【讨论】:

    【解决方案2】:

    您应该使用 any[] 类型转换为数据数组

    this.http.get('mylink.co.uk')
      .map((response: Response) => <any[]>response.json())
      .subscribe(data => {
        console.log(data);
        this.details = data;
        resolve(this.details);
      });
    

    更新 1:

    您应该使用接口并创建相关属性并将它们绑定到 API 接口返回的结果应该是

    export interface Reciepe {
    
        criteria: Criteria;
        matches: Matches;
        faceCounts: any;
        totalMatchCount: number;
        attribution: Attributes;
    }
    
    export interface Criteria {
    
        q: any;
        allowedIngredient: any;
        excludedIngredient: any;
    }
    
    export interface Matches {
        imageUrlsBySize: ImageUrlsBySize;
        sourceDisplayName: string;
        ingredients: string[];
        smallImageUrls: string[];
        recipeName: string;
        totalTimeInSeconds: number;
        attributes: Attributes;
        flavors: any;
        rating: number;
    }
    
    export interface Attribution {
        html: string;
        url: string;
        text: string;
        logo: string;
    
    }
    export interface ImageUrlsBySize {
    
        90: string;
    
    }
    export interface Attributes {
        course: string[];
    }
    

    你的打字稿代码应该修改为

    this.http.get('mylink.co.uk')
      .map((response: Response) => <Reciepe>response.json())
      .subscribe(data => {
        console.log(data);
        this.details = data;
        resolve(this.details);
      });
    

    【讨论】:

    • 谢谢你,但它似乎没有任何区别?
    • 数组中有数组吗?你想打印元素 绑定它到你的数据对象?
    • 我已经用当前有效的代码更新了我的问题,并已经打印出对象,以使我的目标更加清晰。已经起作用的是它们的列表,它通过 object -> 匹配,然后每个项目 这个只是通过 object 我卡住的地方
    • 您可以在团队查看器中使用吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-17
    • 2020-10-17
    相关资源
    最近更新 更多