Angular is disregarding certain JSON fields when creating objects

My goal is to fetch data from the wagtail API, but it returns the JSON in a complex format.

{
    "id": 3,
    "meta": {
        "type": "home.HomePage",
        "detail_url": "http://localhost:8000/api/v1/pages/3/"
    },
    "parent": null,
    "title": "Homepage",
    "body": "<h2>cool an h2 fgf</h2>",
    "main_image": {
        "id": 1,
        "meta": {
            "type": "wagtailimages.Image",
            "detail_url": "http://localhost:8000/api/v1/images/1/"
        }
    },
    "header_image": {
        "id": 1,
        "meta": {
            "type": "wagtailimages.Image",
            "detail_url": "http://localhost:8000/api/v1/images/1/"
        }
    },
    "show_in_menus": true,
    "full_url": "/media/images/Background-4.original.jpg"
}

What I really need is a simpler class structure like this.

export class HomePage {
  id: number;
  title: string;
  body: string;
  full_url: string;

}

However, when I receive the data from the service and try to log it, it shows as undefined.

Is there a way to filter out the unwanted fields from the JSON in typescript?

The service I am utilizing:

import { Injectable } from '@angular/core';
import {Http, Response} from '@angular/http';
import {Observable} from "rxjs";
import {HomePage} from "./HomePage";

@Injectable()
export class HomePageService {

  constructor(private http: Http){
  }

  getHomePage(GUID: number): Observable<HomePage>{
    return this.http
      .get("http://localhost:8000/api/v1/pages/" + GUID + "/")
      .map(this.extractData)
      .catch(this.handleError);
  }
  private extractData(res: Response) {
    let body = res.json();
    return body.data || {}
  }
  private handleError (error: Response | any) {
    // In a real world app, we might use a remote logging infrastructure
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
  }
}

And the component:

import {Component, OnInit, OnDestroy} from '@angular/core';
import {HomePageService} from './home-page.service';
import {ActivatedRoute} from '@angular/router';
import {HomePage} from "./HomePage";

@Component({
  selector: 'app-home-page',
  templateUrl: './home-page.component.html',
  styleUrls: ['./home-page.component.css'],
  providers: [HomePageService]
})
export class HomePageComponent implements OnInit, OnDestroy{
  id: number;
  private sub: any;
  public homePage: HomePage;
  errorMessage: string;
  constructor(private homePageService : HomePageService, private route: ActivatedRoute) {

  }

  ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
      this.id = +params['id'];
    });
    this.homePageService.getHomePage(this.id)
      .subscribe(
        homePage => this.homePage = new HomePage(homePage),
        error =>  this.errorMessage = <any>error,
        () => console.log(this.homePage.full_url)
      );
    console.log(this.id);
  }
  ngOnDestroy() {
    this.sub.unsubscribe();
  }

}

Answer №1

mainPage => this.mainPage = new MainPage(mainPage)
- it seems like there is no constructor defined for the MainPage class in your code. Consequently, passing the mainPage object to it won't trigger any action. Consider implementing the following:

export class MainPage{
    id: number;
  title: string;
  content: string;
  url: string;

  constructor(mainPageObj: any)
  {
      if (mainPageObj)
      {
          this.id = mainPageObj.id;
          this.title = mainPageObj.title;
          this.content = mainPageObj.content;
          this.url = mainPageObj.url;
      }
  }
}

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

What is the internal mechanism used by Angular for routing implementation?

My traditional belief about web browsers has been challenged by the behavior of Angular. I used to think that when a user enters a new URL, the browser would fetch a whole new page from the network and display it, replacing the old one. But with Angular, ...

Designing the Pull to Refresh feature in Nativescript Angular

I've been experimenting with the Nativescript Angular Pull to Refresh Styling demo (Link) and I'm running into an issue where this.myListViewComponent remains undefined, causing the following snippet not to trigger: if (this.myListViewComponent ...

What is the reason for Angular Cli using CommonJs in tsconfig.spec.json?

While reviewing the files created by Angular CLI, I observed that tsconfig.spec.json is configured to use commonJs as the module format, whereas tsconfig.app.json is set up for es2015. Is there a specific rationale for selecting different module implement ...

Adding JSON data to an array in Angular JS using the push method

I am encountering difficulties with adding data to an existing array. Currently, I have set up a table to display the data, but I want to also include the data in the table when a user enters an 8-digit barcode. Factory angular.module('app.pickU ...

Is there a more concise method for accepting a collection of interfaces in TypeScript?

Issue I am facing a simplified version of a problem with my model: Here is how my model currently looks: interface Instrument { name: string; // ...more properties shared by all instruments... } interface Guitar extends Instrument { type: &q ...

Tips for converting a base64 encoded string to a normal string in Swift

Obtaining the readme data for a selected repository from the GitHub api has proven to be a challenge. The "content" seems to be in base64 format, and while attempting to convert it I encountered a fatal error: "Fatal error: Unexpectedly found nil while unw ...

Converting JSONSchema into TypeScript: Creating a structure with key-value pairs of strings

I am working with json-schema-to-typescript and looking to define an array of strings. Currently, my code looks like this: "type": "object", "description": "...", "additionalProperties": true, "items": { "type": "string" ...

Using form-urlencoded data in Angular 5 applications

I have been working on an application that combines a Spring backend with an Angular 5 frontend. The login functionality is secured using Spring Security, and in the frontend, I am trying to send the login data as x-www-form-urlencoded. However, the backen ...

URLs embedded in a JSON string

Currently, I am using an angular template to display JSON data in a calendar format showing various events. I am wondering if it's possible to include URL links within a string in the JSON data. Here is an example: { "name" : "Lee Morgan", ...

Assign the onClick function to the decoration of a Vscode extension

When I click on a vscode decoration, I want to trigger a function. Here's the code I created for this: const decoration = { range, hoverMessage: `${command} ${input}`, command: { title: 'Run Function', command: ' ...

Issue with displaying error message and disabling button as Keyup event fails to trigger

Is there a way to assess the user's input in real-time on an on-screen form to ensure that the pageName they enter is not already in the navbarMenuOptions array? If it is, I want to switch the visibility of displayName and displaySaveButton. However, ...

Is it feasible to develop a Grafana datasource plugin that does not rely on an external backend system?

I am in the process of developing a Grafana datasource plugin that operates independently without relying on an external backend. My plugin is based on the simple-json datasource plugin available at: https://github.com/grafana/simple-json-datasource In a ...

Unlocking the secrets of retrieving the URL query string in Angular2

I'm struggling to extract the URL query string returned by the security API, resulting in a URL format like this: www.mysite.com/profile#code=xxxx&id_token=xxx. My goal is to retrieve the values of code and id_token. In my ngOnInit() function, I ...

Angular throws an error when trying to parse undefined data outside of an async function

I'm having trouble parsing data retrieved from an http call and passing it to ngOnInit. Can you assist me in finding a solution? My project is built with Angular 4. Here's the async function: async getAsyncData() { this.asyncResult = awai ...

Problem encountered in a simple Jest unit test - Unexpected identifier: _Object$defineProperty from babel-runtime

Struggling with a basic initial test in enzyme and Jest during unit testing. The "renders without crashing" test is failing, as depicted here: https://i.stack.imgur.com/5LvSG.png Tried various solutions like: "exclude": "/node_modules/" in tsconfig "t ...

Retrieving JSON data containing peculiar characters and numerical values in iPhone SDK

I have been working on creating an iOS app that retrieves data from a SQL server using a PHP file in JSON format. The app functions perfectly when tested on Safari browser, and I have utilized the SBJSON framework to handle the JSON within my application. ...

Dynamically manipulate menu items in material-ui and react by adding, removing, editing, or toggling their state

I have scoured every corner of the internet in search of an answer to this dilemma. Imagine a scenario where there is a menu located at the top right of a navigation bar, initially showcasing TWO options (1. Login. 2. Register). When a user clicks on eithe ...

Utilize PrimeNG's async pipe for lazy loading data efficiently

I have a significant amount of data (400,000 records) that I need to display in a PrimeNG data table. In order to prevent browser crashes, I am looking to implement lazy loading functionality for the table which allows the data to be loaded gradually. The ...

Using arrow functions in Typescript e6 allows for the utilization of Array.groupBy

I'm attempting to transform a method into a generic method for use with arrow functions in JavaScript, but I'm struggling to determine the correct way to do so. groupBy: <Map>(predicate: (item: T) => Map[]) => Map[]; Array.prototype ...

Removing a value from an array of objects in Angular 2

There is a single array that holds objects: one = [ {name: 'Name', key: '4868466'}, {name: 'Name', key: '4868466'}, {name: 'Name', key: '4868466'}, {name: 'Name', key: & ...