Making a HTTP Get request for a single item in Ionic 2

I have successfully implemented an API to retrieve data and display it on the page. It works perfectly for a json response containing more than one object, as it follows a "matches" hierarchy. However, I am facing an issue when trying to print out data for just one object.

The Json that is working and displaying properly is:

https://i.sstatic.net/M72Dw.png

Here is the code snippet that is working:

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

Typescript code:

this.http.get('http://api.yummly.com/v1/api/recipes?_app_id=397aed16&_app_key=69e2565adcec7a6609b18bef31261e62')
  .map(res => res.json())
  .subscribe(data => {
    console.log(data);
    this.listing = data.matches;
    resolve(this.listing);
  });

I am currently stuck while working with the following Json:

https://i.sstatic.net/M72Dw.png

This is my request:

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

And in Angular, I'm trying to display {{attribution}}

If anyone could provide some guidance on where I might be making a mistake, that would be highly appreciated.

Answer №1

It is recommended to utilize any[] for typecasting to an array of data.

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

Update 1:

The best practice involves using an interface and defining the necessary properties to bind them to the API's returned result. An example interface could be as follows:

export interface Recipe {

    criteria: Criteria;
    matches: Matches;
    faceCounts: any;
    totalMatchCount: number;
    attribution: Attributes;
}

// Additional interfaces defined here...

Your TypeScript code should be updated like so:

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

Answer №2

Try following this example, I found it helped me solve my issue. Here are the resources I used:

Angular HTTP Guide

Google JSON Style Guide

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

For more information, check out this reference: Mapping API Objects in Ionic

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using JavaScript, you can add an article and section to your webpage

Currently, I am utilizing AJAX to showcase posts. My objective is to extract each property from a JSON object that is returned and generate an <article> for the title followed by a subsequent <section> for the content. While I can successfully ...

Encountering error "An import path cannot end with a '.ts' extension." when importing TypeScript file in Vue Single File Component (SFC) within VS Code

Currently, I am in the process of transitioning my .vue components from using JavaScript to TypeScript. As a result, my single file components are structured as follows: <template> ...something... </template> <script lang="ts"> import ...

Jasmine reported that there were no specifications found in the Angular project written in TypeScript

I'm facing a frustrating issue with Karma and Jasmine in my Angular 9 project. Despite setting up the configuration files correctly, I keep getting a "No specs found" message when running ng test. I have tried various adjustments, including creating d ...

Saving even and odd digits in a collection

We were given the challenge of creating a program that allows the user to input ten numbers and then categorize them into either an Even or Odd Array. Accept 10 inputs from the user. Categorize each number as even or odd into separate arrays. Display how ...

Issues with running NPM script for compiling TypeScript code

[UPDATE] Initially, I resolved this issue by uninstalling tsc using npm uninstall tsc (as recommended in the response marked as the answer). However, the problem resurfaced after some time, and eventually, I found success by utilizing Windows Server for L ...

Using ORACLE SQL to deserialize JSON data

I'm working with a JSON object that is serialized and looks like this: { "Sender": "Service", "Type": "SPIGlassAuditedOrder", "Data": "{\"Header\":{\"Id\":\"ASDFDSA-8687689-ASDFD\",\"EventType\":\"Order&bs ...

Parsing string to JSON object and extracting specific information

In my code, I have a variable named "response" that contains the following string: {"test": { "id": 179512, "name": "Test", "IconId": 606, "revisionDate": 139844341200, "Level": 20 }} My goal is to extract the value of the id key and store ...

Utilizing the Google Geocode API to handle a promise with a substantial array

My Objective To efficiently process a large array using the .map method and interact with the Google Geocoder API through promises to get location data. The goal is to utilize Promise.all to store results in a .json file upon completion of the operation. ...

Obtain information from a web address using Ionic framework

Hello, I am experiencing an issue with retrieving data from a URL in my Ionic application. When using @angular/http to fetch a JSON object from the URL, everything works fine in the browser when running 'ionic serve'. However, when deploying the ...

Determine the presence of a JSON Value/Array in a web application using JavaScript and visualize the information in a dynamic

Utilizing the Ticketmaster API has provided me with a sample dataset from their platform, Data 1 - Including information on "presales." "sales": { "public": { "startDateTime": "2019-11 ...

Sending VSCode to external functions

My primary entrypoint containing the activate() function is: extension.ts import * as vscode from "vscode"; import { subscribe } from "./eventListeners.ts"; export function activate(context: vscode.ExtensionContext) { vscode.command ...

Combining Kafka as the source with mqtt and using jdbc as the sink

I am using Kafka and have configured a MQTT broker as the data source. The JSON configuration for this setup is as follows: { "name": "mqtt-source", "config": { "connector.class": "io.confluent.connect.mqtt. ...

Accessing the various types within a monorepo from a sibling directory located below the root folder

Seeking assistance in resolving a referencing types issue within a TypeScript monorepo project. Unsure if it is feasible given the current setup. The project structure is as follows: . ├── tsconfig.json ├── lib/ │ └── workers/ │ ...

Transform the CSS to a Mat-Form-Field containing a search box within it

I am currently working with Angular, Angular Material, and SCSS for my project. Here is the front-end code snippet that I am using: <mat-form-field class="custom-form-field" style="padding-top: 5px;padding-bottom: 0px; line-height: 0px; ...

@JsonFilter: Enhancing performance through customization

In the process of developing a REST API that must support optional filtering of properties based on a request parameter, I am exploring ways to achieve this using Spring MVC 3.0.x and Jackson. My aim is to receive a string parameter (in the format "fieldN ...

Utilizing Logical Operators in Typescript Typing

What is the preferred method for boolean comparisons in Typescript types? I have devised the following types for this purpose, but I am curious if there is a more standard or efficient approach: type And<T1 extends boolean, T2 extends boolean> = T1 ...

Deciphering JSON data in classic ASP

I am currently working on integrating our ERP system with our website. I have managed to receive a JSON response from the system, but I need assistance in parsing it properly. To help me with this task, I am using ASPJSON (www.aspjson.com). My main quest ...

How can I retrieve the Google Maps URL containing a 'placeid' using AJAX?

I have a specific URL that I can access through my browser to see JSON data. The URL appears as follows: https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJZeH1eyl344kRA3v52Jl3kHo&key=API_KEY_HERE However, when I attempt to use jQuer ...

Button for liking and disliking with Angular, Node.js, and

On my Twitter-esque website, I am developing YouTube-style (like-dislike) buttons. However, when it comes to implementing these like-dislike buttons using Angular, Node.js, and MYSQL with NgFor loop and ngIf conditions, I encountered a problem. My database ...

No input in ng2-select2

How can I reset the value in ng2-select2 by clicking on a button? Here is my current HTML code: <select2 id="bill" [data]="colBill" [options]="option" (valueChanged)="onBillArray($event);"> The corresponding Typescript code is: this.arrBill = []; ...