Retrieve and present JSON information (object, array) using a service provider in Ionic 2 with TypeScript and Angular 2

I am currently delving into Angular 2 and Ionic 2 (not to forget about NodeJS and TypeScript).

For testing purposes, I have a list of users available here. Eventually, I will be fetching real user data from an API connected to my database.

To handle this, I created a provider within my Ionic 2 project named test-service.ts which contains the following code:

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class PeopleService {

  public users: any[];

  constructor(public http: Http) {
    this.users;
  }

  load(){
    this.http.get('https://demo6000522.mockable.io/test')
    .map(res => res.json())
    .subscribe(
      data => {
        this.users = data;
        console.log(this.users);
        return Promise.resolve(this.users)
      },
      err => {
          console.log("No users found!");
      }
    );
  }
}

The retrieved user data is stored in an array called "peoples." You can view it by accessing the above URL.

In the file users.ts, the following code is present:

import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
// importing the service here
import {PeopleService} from '../../providers/test-service';

@Component({
  selector: 'page-users',
  templateUrl: 'users.html',
  // Importing the service to use the api
  providers: [PeopleService]
})
export class UsersPage {

  constructor(public navCtrl: NavController, public navParams: NavParams, public peopleService: PeopleService) {
    this.loadPeople();
  }

  loadPeople(){
    this.peopleService.load()
  }
}

Finally, in the file users.html:

<ion-header>
    <ion-navbar>
        <button ion-button menuToggle>
            <ion-icon name="menu"></ion-icon>
        </button>
        <ion-title>Users</ion-title>
    </ion-navbar>
</ion-header>

<ion-content padding>
  <ion-list>
    <ion-item *ngFor="let user of users">
      <p>{{ user.fistname }}</p>
      <p>{{ user.lastname }}</p>
      <p>{{ user.email }}</p>
    </ion-item>
  </ion-list>
</ion-content>

Although no errors are encountered and the data is successfully fetched in the console browser, there seems to be an issue with displaying it in the Ionic view as seen in the screenshot below:

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

Note: Disregard the WebSocket connection error mentioned. It's unrelated to the current query. Thank you.

How can I properly display my JSON data in the view?

Answer №1

  1. Utilize the peoples property from your response:
this.users = data['peoples'];

--> Your users variable is currently receiving the entire returned object instead of just the user-array.

  1. Access the users variable from your service:
<ion-item *ngFor="let user of peopleService.users">

--> Your template is searching for a users variable within your component, which doesn't exist and therefore results in undefined. Using *ngFor with undefined will yield nothing. :)

UPDATE

A more elegant approach:

  1. Implement a BehaviorSubject:
public users = new BehaviorSubject<any /* or your class-type */>([] /* initial value */);
  1. Keep your BehaviorSubject updated:
public refresh () {
   this.http.get('https://demo6000522.mockable.io/test')
      .map(res => res.json())
      .map(res => res['peoples'])
      .subscribe(
         ppls => this.users.next(ppls),
         err => {
            console.log("It seems like there are no users here!");
      });
}

3.1. Utilize it in your template:

<ion-item *ngFor="let user of peopleService.users | async">

3.2. Or subscribe to it and maintain a local copy within your component:

private _users: any[];

ngOnInit() {
   this._users = this.peopleService.users.value; // Retrieve the current value from our BehaviorSubject
   this.peopleService.users.subscribe(ppls => this._users = ppls); // Subscribe to changes!
   this.peopleService.refresh();
}
<ion-item *ngFor="let user of _users">

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

Error loading jakefile: Unable to load file

After attempting to use Jake, I encountered a strange issue where Jake was unable to load the Jakefile. Any suggestions on how to resolve this? Directory Structure: jake_test >> jake.sh jake_test >> jakefile.js jake.sh file node_modules/.b ...

Big calendar experience with React

Currently, I am developing a calendar page as part of my group project. Utilizing react big calendar for this purpose, I am facing an issue where the text displayed in the popup window needs to remain unchanged by the user. With multiple events on the ca ...

Is there a way to convert Summernote text to plain text by extracting it from JSON data through an Ajax request

I have been utilizing the Summernote text editor to enter information, but now I am facing an issue where all the data is being displayed with HTML tags. How can I convert this formatted data into plain text? https://i.stack.imgur.com/Rkx4B.png ...

Changing JSON dictionary into a Pandas Dataframe

I'm facing a challenge with converting a JSON dictionary into a Pandas DataFrame due to the nested structure. Here's an example of how the JSON dict is structured: { "report": "{'name':{'data':[{'key 1&a ...

The array is not being updated with the new value entered in the input field for "address"

Currently, I have a table that loops through an array and displays the content in a list format. The address field is displayed as an input with the value set to :value="location.address". The input fields are initially disabled, but when the ed ...

Is there a way to access a header value using nodejs and express?

Is there a way to retrieve the x-api-key value sent in the header of my endpoint using the GET method? The code works fine on my localhost but it throws an error on the server. Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the ...

Nextjs and Typescript are giving me an error that says, "The property 'nextUrl' is not found on type 'IncomingMessage'." What could be causing this

I'm currently utilizing the Next.js API route and attempting to retrieve the request parameters: export const GET = async (req: IncomingMessage) => { const matchString: String = req.nextUrl.searchParams.get("data") } I assume the typ ...

What is the most effective way to utilize forms in order to send information from both an input field and a dropdown selection menu with just one button click

Currently utilizing Material UI and React for my project. I am dealing with data from a text field and a drop down select that I want to be 'submitted' when a button is clicked https://i.sstatic.net/fvxo0.png Below is the code with unnecessary ...

What's the verdict on Ajax requests in Angular 4 - is $ajax superior to $http?

Instead of using $http to fetch data, I am utilizing $.ajax({}) in Angular 4. Is this a good approach for making AJAX calls? What is the recommended method for handling this task? Currently, I am employing this particular method for my AJAX requests. $. ...

Building a personalized version with core-js

I am currently in the process of developing a custom build using core-js. Following the instructions provided, I initiated the following commands: npm i core-js && cd node_modules/core-js && npm i The process seemed to go smoothly. Then, ...

Using jQuery to choose options and change the background color

Hey there, I have a select box below: <select id="events"> <option value="1" style="background-color:green;">Event 1</option> <option value="2" style="background-color:yellow;">Event 2</option> <option value="3 ...

How shouldjs makes value verification effortless for unordered arrays

In my express.js application, I'm currently using supertest and should.js as my preferred testing framework. However, I've encountered some difficulties when it comes to testing for specific values within an unordered array. After referring to t ...

Checking the status of a mongos connection in Node.js: A simple guide

Imagine a scenario where our Node.JS app is connected to the Mongos process, but suddenly Mongos crashes. How can our app be notified of this failure? var db = null; mongo.MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, mydb ...

Inquiry regarding the implementation of DTO within a service layer parameter

I have a query regarding the choice of service layer to use. // 1 export class SomeService{ async create(dto:CreateSomeDto) {} } or // 2 export class SomeService{ async create(title: string, content: string) {} } It appears that most individuals opt ...

Creating a function that allows for the dynamic addition of rows in Angular with

I am currently working on implementing search and filter functionality, which requires adding rows dynamically. With hundreds of fields to filter, my boss has decided to organize them in dropdown menus (such as Manager, City, and Name in this example). The ...

dehydrate the subordinate resource field in a flavorful manner

Recently, I came across tastypie and I have found it to be truly amazing. However, I am facing some challenges while trying to manipulate the JSON output. For instance, consider the following code snippet: ... class UserResource(ModelResource): class ...

Function starting too slow due to rapid Loading Spinner Image display

I am struggling with a function that is supposed to display the contents of posts when clicked on. My goal is to have a loading spinner appear for a few seconds before the post content shows up. However, I am facing an issue where the spinner only appears ...

Evolution of ReactJS state over time

When working with React, I wanted to increment a state variable called progressValue by 0.1 every 500 ms until it reaches 100. Here's what I initially tried: const [progressValue, setProgressValue] = React.useState<number>(0) const tick ...

Cloud Foundry deployment faces startup issues

I attempted to deploy my Node.js application on Bluemix, but encountered a failure. After executing cf logs IssueTracker --recent, I came across the following error: 2018-12-10T16:50:24.38+0000 [APP/PROC/WEB/0] ERR module.js:549 2018-12-10T16:50:24 ...

Adjusting font size in dynamic containers relatively

Imagine we have a slider named .outer, which adjusts its height based on the width of the viewport. Inside this slider, there is an example slide called .inner that contains some text. However, when we shrink the window width, the content in slide .inner s ...