HTTP获取请求单个对象离子2

时间:2017-02-11 16:31:12

标签: arrays json angular object typescript

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

Json我有工作,可以打印出来

enter image description here

和可行的代码

<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坚持并且坚持

Json data

我的要求是

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

和angular为{{attribution}}

如果有人能够指出哪里出错我会很棒

2 个答案:

答案 0 :(得分:0)

你应该使用任何[] 来强制转换为数据数组

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);
  });

答案 1 :(得分:0)

按照此示例,我认为它将解决您的问题,我遵循了,我也解决了我的问题。

请参阅:

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
  }
}

mock-locations.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