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 npm script for running Protractor is encountering an error

Currently, I am facing an issue while trying to execute the conf.js file using an npm script. The conf.js file is generated within the JSFilesRepo/config folder after running the tsc command as I am utilizing TypeScript in conjunction with protractor-jasmi ...

"Learn how to programmatically close all panels in an ngb-accordion component in Angular 2 Release 6, leaving only

I have recently begun working on an accordion and I am trying to figure out how to make the first panel expand while keeping the others closed. I attempted to use [closeOthers]="true" but it doesn't seem to be effective. Here is my HTML code: <di ...

Tips for ensuring only one property is present in a Typescript interface

Consider the React component interface below: export interface MyInterface { name: string; isEasy?: boolean; isMedium?: boolean; isHard?: boolean; } This component must accept only one property from isEasy, isMedium, or isHard For example: <M ...

Even as I create fresh references, my JavaScript array object continues to overwrite previous objects

Coming from a background in c# and c++, I am facing some confusion with a particular situation. Within the scope of my function, I am creating a new object before pushing it into an 'array'. Strangely, when I create the new object, it appears to ...

I am looking to include both a space and a comma in the State dropdown value in an Angular application

I am facing an issue with my dropdown in Angular 9. When the State is more than one, it displays without any space between them. I want it to show like: Licensed State:ARCA I need like: AR, CA This is the code I have so far: <ng-c ...

Issue in Angular Material: The export 'MaterialComponents' could not be located in './material/material.module'

I'm relatively new to Angular and I am encountering some difficulties when trying to export a material module. The error message that appears is as follows: (Failed to compile.) ./src/app/app.module.ts 17:12-30 "export 'MaterialComponents&ap ...

What steps can be taken to properly set up routing in Angular 4 in a way that organizes feature-modules routes as children in the

Organizational layout of projects: /app app.module.ts app.routing.ts : : /dashboardModule /manage-productModule manage-product.module.ts manage-product.routing.ts Within 'app.routing.ts' [ { path : '&a ...

Unable to initiate ngModelChange event during deep cloning of value

I've been struggling to calculate the sum of row values, with no success. My suspicion is that the issue lies in how I am deep cloning the row values array when creating the row. const gblRowVal1 = new GridRowValues(1, this.color, this.headList ...

Params are not being sent by Angular HttpRequest

I have been attempting to pass parameters in a basic GET request using HttpRequest, but it seems that the parameters are not being sent. let params = new HttpParams(); params.set("page", "4"); let req = new HttpRequest<any>( &q ...

Exploring the power of Vue CLI service in conjunction with TypeScript

I've recently set up a Vue project using the Vue CLI, but now I am looking to incorporate TypeScript into it. While exploring options, I came across this helpful guide. However, it suggests adding a Webpack configuration and replacing vue-cli-service ...

"Utilizing TypeScript with React: Creating a window onClick event type

My linter is not happy with the any type for window.onClick. What should be the correct type? import React, { useContext, useState } from 'react'; import { Link } from 'react-router-dom'; import { Global } from '../globalState&apo ...

Improving my solution with PrimeNG in Angular2 - fixing the undefined tag error

After working with Angular for just three days, I successfully set up a login page dashboard using a web API solution. Everything was working great until I encountered an issue when trying to load the PrimeNG DataTableModule into my components. After searc ...

A guide to adding a delay in the RxJS retry function

I am currently implementing the retry function with a delay in my code. My expectation is that the function will be called after a 1000ms delay, but for some reason it's not happening. Can anyone help me identify the error here? When I check the conso ...

Looking to display parent and child elements from a JSON object using search functionality in JavaScript or Angular

I am trying to display both parent and child from a Nested JSON data structure. Below is a sample of the JSON data: [ { "name": "India", "children": [ { "name": "D ...

Tips for adjusting the position of overflowing text on a website using CSS in real-time

I'm currently working on an Angular application and I'd like to customize the styling so that any text exceeding 128 characters is not displayed. Ideally, if the text exceeds 128 characters, it should move to the left; otherwise, it should remain ...

What steps are involved in generating a Typescript module definition for a directory containing a babel-plugin-content-transformer?

Currently utilizing the babel-plugin-content-transformer to import a directory containing YAML documents in a React Native/Expo project. The configuration for my babel plugin looks like this: ['content-transformer', { transformers: [{ ...

Exploring nested objects and arrays with Plunker - extracting their values

I have retrieved two arrays, each containing nested objects, from API endpoints. One array (preview) consists solely of numbers. For example: [{ obj1:[1, 2], obj2:[3, 4] }] To obtain strings associated with IDs, I made another call to a different en ...

Passing an object from an Angular application to a backend server in Node.js using the

I have a YAML file with the following structure: Layouts: - Name: Default Layout LayoutId : 1 ConfiguredSegments: LiveA : Height : 100 Id : LiveA Ref1A : ...

Issue with handling multiple input files in an *ngFor loop

I am facing difficulties in targeting the correct input within a *ngFor loop. When I include an image with the first input (Certificat dimmatriculation), it displays a placeholder image and a delete button to reset the input, but it appears under both divs ...

Unwrapping nested objects in a JSON array with JavaScript: A step-by-step guide

After trying some code to flatten a JSON, I found that it flattened the entire object. However, my specific requirement is to only flatten the position property. Here is the JSON array I am working with: [{ amount:"1 teine med 110 mtr iletau" comment:"" ...