Unable to retrieve nested objects from HTTP Response

After receiving data from a HTTP Response, I am trying to access and display it in my template. However, despite storing the data into a component variable, I am encountering issues when trying to access specific properties of the object.

{
"files": [ ],
"posts": [
    {
        "content": "This is a test post related to Project 2.",
        "id": 2,
        "name": "Example Post 2",
        "timestamp": "Wed, 10 Aug 2016 19:52:09 GMT"
    }
],
"project": {
    "id": 2,
    "info": "This is the text for Example Project 2",
    "name": "Example Project 2",
    "timestamp": "Wed, 10 Aug 2016 19:50:59 GMT"
    }
}  

I have tried accessing the project id with {{project.project.id}}, but it does not work as expected. The object structure is displayed as follows:

Object { files: Array[0], posts: Array[1], project: Object }  

Despite attempting various solutions such as iterating over the JSON object, I continue to face errors. Here is an exception message that was raised:

Uncaught (in promise): Error: Error in ./ProjectDetailComponent class ProjectDetailComponent - inline template:0:4 caused by: self.context.project is undefined

To provide more context, here are the relevant files:

Component:

@Component({
    selector: 'app-project-detail',
    templateUrl: './project-detail.component.html',
    styleUrls: ['./project-detail.component.sass']
})
export class ProjectDetailComponent implements OnInit {
    private project;
    private errorMessage;

    constructor(private route: ActivatedRoute,
                private router: Router,
                private projectService: ProjectsService) {
    }

    ngOnInit() {
        this.route.params.forEach((params: Params) => {
            let id = +params['id'];
            this.projectService.getProjects(id).subscribe(
                function (project) {
                    this.project = project;
                },
                error => this.errorMessage = <any>error
            );
        });
    }

}  

Service:

@Injectable()
export class ProjectsService {

    constructor(private http: Http) {}

    private projectsUrl = 'http://localhost:2000/api/projects/';

    getProjects(id?: number): Observable<any>{
        if(id){
            return this.http.get(this.projectsUrl + ""+id)
                .map(this.extractData)
                .catch(this.handleError);
        } else {
            return this.http.get(this.projectsUrl)
                .map(this.extractData)
                .catch(this.handleError);
        }


    }

    private extractData(res: Response) {
        let body = res.json();
        return body;
    }
    private handleError (error: any) {
        let errMsg = (error.message) ? error.message :
            error.status ? `${error.status} - ${error.statusText}` : 'Server error';
        console.error(errMsg); 
        return Observable.throw(errMsg);
    }
}

Any assistance or guidance on resolving these issues would be greatly appreciated!

Answer №1

The assigned value is not where you expect it to be.

ngOnInit() {
    this.route.params.forEach((params: Params) => {
        let id = +params['id'];
        this.projectService.getProjects(id).subscribe(

            // function (project) {
            // should be
            (project) => {             // <<<<=== change
                this.project = project;
            },
            error => this.errorMessage = <any>error
        );
    });
}

and access it using

{{project?.project?.id}}

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

The type 'Observable<any>' cannot be assigned to the type 'Observable<T>'

Here is the code I am working with: import {HttpClient} from '@ngular/common/http'; private httpClient: HttpClient; do_request(method: string, url: string, ...

Steps for wrapping a class with a higher order component

Is it feasible to encapsulate a class component within a higher order component (HOC) that is also a class? import React, { Component } from "react"; import { View } from "react-native"; import { Toast } from "react-native-easy-toast"; const withToast = ...

TypeScript: Defining a custom type based on values within a nested object

I'm attempting to generate a unique type from the value of a nested object, but encountering failure if the key is not present on any level of nesting. Can someone point out where I might be making a mistake? const events = [ { name: 'foo&apos ...

How do I determine in Angular (2+) when all child components have been initialized from the parent component?

Is there a lifecycle hook named "ngAfterAllChildrenInit" that can be used because ngAfterViewInit is called before the ngOninit of the children? I am currently trying to find a solution that avoids using setTimeOut or emitting events from all of the child ...

Commitments shatter amidst constructing a website

Utilizing promise and http.get to retrieve data from a JSON API in Wordpress. Once the data is retrieved, it should be displayed on a page... However, an error occurs when attempting to build the page due to the data not being available. What steps can ...

Are child routes permitted to be utilized without the need for router outlets, specifically for tab contents within a main component?

Can different components be rendered for each tab in a tab menu without using router outlets? Within my parent component, there is a template containing a tab menu component with each tab item having an ng template associated with it. I have set the tabs p ...

Utilizing Ace with a personalized theme in Angular 2 application while straying away from the default theme directory

I am currently facing an issue with integrating an Ace editor into my Angular 2 application, which is built using angular-cli. I want to link the Ace editor to a custom theme stored in the app's assets folder src/app/assets instead of within node_modu ...

Filtering relations in TypeORM can be achieved by using various query criteria

Hello, I have a couple of questions regarding TypeORM in TypeScript. Using Find() Only: I have two tables in my database - Users and Sessions. I am interested in retrieving a specific User along with all their Sessions where the sessions_deleted_at column ...

Angular: Changing the class of a parent element dynamically while iterating through a list with ngFor

I have a unique challenge where I am trying to style a checkbox as a button by placing it inside its label. <label> <input type="checkbox" name="..."> </label> My goal is to toggle the parent label's class based on whether the che ...

Issue with populating virtual IDs in NestJS mongoose schema containing an array of schemas

In the schema provided below, I have defined the structure for Map, Marker, and Desk: export type MapDocument = Map & Document @Schema({ timestamps: true, versionKey: false, id: true }) export class Map { constructor(partial?: Partial< ...

Nest is having trouble resolving dependencies for this service

Can multiple MongoDB models be injected into one resolver and used? I attempted to accomplish this by first adding the import of SectionSchema and SectionsService to the PostsModule: @Module({ imports: [MongooseModule.forFeature([{name: 'Post&apos ...

Generate random entries from an object based on specific criteria and append them to a fresh object using Typescript

Experimenting with Ionic2 and Typescript has been my recent focus. I have an object that contains various meals, calorie counts, and meal types (such as vegan). This is how the object looks: [ { "id":14093, "name":"Proteinshake mit Wasser ...

What is the best way to extract items from another array that have approved IDs - is it through using map(), filter(),

I am unsure about the best approach to retrieve only the items (array with objects) that have been approved based on their id. Should I start by using map() and then filter(), or should I filter() them first and then map()? export class AppComponent { ...

Building applications for platform iOS is not supported on this operating system

I'm currently exploring the features of NativeScript + Angular + SQLite for building a mobile application, and I am referencing this video as a guide. However, when I reached the 3:00 mark, it instructed me to execute the command tns platform add ios ...

Adjust the colors dynamically based on specific data within a loop

My task involves populating a table with data. Specifically, I am focusing on coloring the data in the first year column according to certain conditions. The desired outcome is as follows: +--------+------------+------+------+ | YEAR | 2022 | 2021 ...

Traversing a sequence of method calls within a Promise object (as the return type)

In software development, there is a classic technique where a method returns the result of another method call: method1(): ObjectX { if( condition1 ) return method2(); return undefined // or some default value; } method2(): ObjectX { let r ...

Unlocking the union of elements within a diverse array of objects

I have an array of fields that contain various types of input to be displayed on the user interface. const fields = [ { id: 'textInput_1', fieldType: 'text', }, { id: 'selectInput_1', fieldType: 'sel ...

An error is triggered by Angular when attempting to create a new application due to an invalid project name

Attempting to develop an Angular app for my website: ng new jon-sud.io Encountering an error in Angular: The project name "jon-sud.io" is considered invalid. I am aiming to create an Angular app with the folder named jon-sud.io, not jonSudIo. Why does ...

How to retrieve an array of objects with Express, Node JS, and Angular by making an HTTP Get call

After following a tutorial on setting up an Angular app with an Express server using Node.js from , I attempted to send a GET request to retrieve an array of objects with the code below: import { Component, OnInit } from '@angular/core'; import ...

"Struggling with setting the default checked state for single and multiple checkboxes? The ng-init method with checkboxModel.value=true seems to be ineffective – any suggestions

<input type="checkbox" ng-model="isChecked.value" ng-true-value="'yes'" ng-false-value="'no'" ng-click='handleCheckboxChange(isChecked.value, idx);' ng-init="isChecked.value=true" /> ...