Unable to properly display data onto view in Ionic 2 (using Angular 2 and TypeScript)

I am facing an issue with Ionic 2. I have a problem where I need to display a card component using *ngFor with the title of an article and other data such as thumbnails, etc. When I hardcode values in the array, the card shows up fine. However, when I use a REST API, the card does not get rendered even though the data is retrieved successfully.

Is there something similar to $scope.$digest(); in Angular 1 to apply changes on $scope for Angular 2 (Ionic 2)? Or is there another way to achieve what I want?

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import * as $ from 'jquery';
import * as moment from 'moment';
var itemList =[];
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})

export class HomePage  {

constructor(public navCtrl: NavController) {
    moment.locale('id');
    this.getNews();
}

getNews(){
    $.ajax({
      url: secret_api_url ,
      dataType:"jsonp",
      method:"get",
      success:(data =>{
        var post = data.posts;
        post.forEach(function(p){
          p.date = moment(p.date).format('lll');
          itemList.push(p);
        });
        // itemList = post;

      }),
      error:(err =>{
        console.log("Error",err);
      })
    });
}
<ion-card padding *ngFor="let item of itemList;">

<ion-card-content>
< label style="color:white;">
{{i}}
<label class="timestamp">{{ item.date }}</label>
</label><br>
<small>
<i>
{{ item.short_desc }}
</i>
</small>
<ion-card-title>
{{item.title}}
</ion-card-title>
</ion-card-content>
<img src="{{item.img_url}}"/>
</ion-card>

Answer №1

Make sure to properly convert data retrieved from your API into class instances:

export class BlogPost {
    constructor(public postId: string, public postTitle: string) {}
}

// Your component:

this.posts: Array<BlogPost> = [];

ngOnInit() {
    this.blogPostService.getPosts()
        .subscribe(posts => { 
                this.posts = posts.map(item => new BlogPost(item.postId, item.postTitle);
            }); 
});      
}

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

Sharing interfaces and classes between frontend (Angular) and backend development in TypeScript

In my current project, I have a monorepo consisting of a Frontend (Angular) and a Backend (built with NestJS, which is based on NodeJS). I am looking to implement custom interfaces and classes for both the frontend and backend. For example, creating DTOs s ...

Creating a React component with multiple prop types using Typescript

In this particular component, the requirement is to input a config object that can be of two types - either an object containing a "name" property (which should be a string), or a boolean value indicating that the config object has not been set yet. type C ...

Troubleshooting the unexpected behavior of the shareReply() method in Angular version 15

Utilizing the same API across 3 components can lead to duplicate HTTP calls. To prevent this, I decided to cache the response using shareReply() from RxJs so it can be reused wherever needed. Here's how I implemented it: api-service.ts getUsers(): Ob ...

Loading children routes using NgRx

In my Angular 9 app, I am facing a challenge where I need to dynamically load a specific module only when a certain property in my app state (ngrx) is not null. Currently, I have an AuthGuard set up in my routes using canActivate. My goal is to load the & ...

What could be causing the Angular imports to not function properly?

I've recently set up a project, and it's compiling successfully. However, every time I attempt to add a directive like [formGroup], it throws an error such as "Property formGroup is not provided by any applicable directives nor by form element". ...

The expect.objectContaining() function in Jest does not work properly when used in expect.toHaveBeenCalled()

Currently, I am working on writing a test to validate code that interacts with AWS DynamoDB using aws-sdk. Despite following a similar scenario outlined in the official documentation (https://jestjs.io/docs/en/expect#expectobjectcontainingobject), my asser ...

Challenges with Angular observables

Struggling to make observables work has been quite the challenge for me lately. My code now resembles a chaotic battleground rather than the organized structure it once was. The dreaded "ERROR TypeError: Cannot read property 'map' of undefined" ...

The property 'licenses' has incompatible types. The type 'License[]' cannot be assigned to type 'undefined' in the getServerSideProps function while using iron-session

I am encountering an issue with red squiggly lines appearing on the async keyword in my code: Argument of type '({ req, res }: GetServerSidePropsContext<ParsedUrlQuery, PreviewData>) => Promise<{ props: { admin: Admin; licenses?: undefined ...

Angular 8: Bridging the gap between two players with a shared singleton service

I've been working on creating a multiplayer Battleships game, and although the basic functionality is there, I'm struggling to connect two players to the same game. Any assistance would be greatly appreciated! My goal is to create a service that ...

Nestjs: Step-by-step guide to removing a specific application from a Nestjs monorepo using nest/cli

Is there a method to delete a specific app within a nestjs monorepo using the nest/cli? I have searched through the documentation and developer forums but cannot seem to find a solution. ...

Exploring the Latest Features: Using Angular 7 with Bootstrap Collapse for Dynamic Aria-Controls

I am currently working on creating my own component to use within an *ngFor loop. I am facing an issue where I need a unique value for my Collapse feature. Right now, when I click on the second main row in the table, the collapse feature only shows the inn ...

Updating the log file location for electron-log in an Angular application integrated with Electron

I am currently developing a project using Angular 6 integrated with Electron. I have managed to successfully incorporate the electron-log library using ngx-electron. As a result, my application is functioning well and logging data to the default path: C:&b ...

Using getter functions and Visual Studio for TypeScript

In my TypeScript classes in Visual Studio, I have been implementing getter functions. I find that using getter functions helps to clean up my code, although there is one issue that I would like to address. class Foo { doWork(){ console.log(this.bar ...

Using TypeScript, we can assign a JSON object to an extended class by leveraging the

Task was to include an additional property. I modified a current class by adding a new property, but when I assign a JSON object from the database, the newly added property disappears. Is there a way to correctly assign a JSON object to a TypeScript class ...

Mocking a common function in a shared service using Typescript and Jest

I have a service that is utilized with NestJS, although the issue at hand is not specific to NestJS. Nonetheless, testing in NestJS is involved, and I use it to create the service for testing purposes. This service is responsible for making multiple calls ...

Webpack may suggest, "An extra loader might be needed" within a React.js project

I recently created a React project with two separate workspaces, named 'webmail' and 'component'. In the 'component' workspace, I added a small tsx file that I wanted to utilize in the 'webmail' workspace. Below is t ...

Generate gzipped files using Angular CLI

I am attempting to populate a dist folder with the standard files along with their .gz versions. To achieve this, I used ng eject to obtain the webpack.config.js file in order to integrate the compression plugin from https://github.com/webpack-contrib/comp ...

What is the best way to retrieve an object when a value is not found? Consider implementing a looping mechanism with a specific condition in React and TypeScript to successfully

Greetings, I am faced with an array of objects structured as follows: const arr_obj = [ { id: '1', jobs: [ { completed: false, id: '11', run: { ...

Icon Searchbar Feature in Ionic 2

I am currently working with Ionic2 and have integrated the ion-searchbar component into my project: https://i.sstatic.net/CqmF4.png Question Would it be possible to customize the search icon? The default icon is a magnifying glass, but I would like to r ...

`Is there a way to effectively test an @Input component in Angular?`

Despite multiple successful attempts in the past, I am facing some difficulty getting this to function properly. Within my component, I have an input @Input data: Data, which is used in my template to conditionally display certain content. Oddly enough, du ...