Unable to Pass Nested API Object from Parent to Child Component in Angular 11

I've hit a roadblock with this issue that's been puzzling me for a few days now. The flow of the application goes as follows:

Call API -> Receive Response -> Display Results in Parent Component -> Pass Results from Parent to Child When a User Clicks a Result.

The challenge lies in the last step, where I'm struggling to pass a nested result from my Parent component (missionList) to my Child component (missionDetails)

When I try to access the property 'mission_small_patch' in the HTML file of the Child Component, it throws an error saying Property 'mission_small_patch' does not exist on type 'ILinks[]'

What confuses me is that simply re-saving my Interface file makes the image appear in the Child Component upon reloading the application! This inconsistency baffles me, as I know the property exists and I believe I'm accessing it correctly.

I'm at a loss trying to figure out what I might be overlooking here. Could it be related to how I display data in the Parent component using a custom pipe? I've also attempted to modify the getMission() method in the parent to map the values like this, but still no luck:


getMission():void{
 this.service.subscribe((resp:any)=>{
    this.mission_patch_small = resp.map(r => r.links)
})
}

The external API response provides me with a nested object, specifically targeting the links: mission_patch_small

"flight_number": 1,
"mission_name": "FalconSat",
 "launch_failure_details": {
      "time": 33,
      "altitude": null,
      "reason": "merlin engine failure"
    },
    "links": {
      "mission_patch": "https://images2.imgbox.com/40/e3/GypSkayF_o.png",
      "mission_patch_small": "https://images2.imgbox.com/3c/0e/T8iJcSN3_o.png",
      "reddit_campaign": null,
      "reddit_launch": null,
      "reddit_recovery": null,
      "reddit_media": null,
      "presskit": null,
      "article_link": "https://www.space.com/2196-spacex-inaugural-falcon-1-rocket-lost-launch.html",
      "wikipedia": "https://en.wikipedia.org/wiki/DemoSat",
      "video_link": "https://www.youtube.com/watch?v=0a_00nJ_Y88",
      "youtube_id": "0a_00nJ_Y88",
      "flickr_images": []
    },
    

Despite creating an interface for the received data, including an additional field mission_patch_small, I can't seem to access this property. I even tried changing the type of mission_patch_small to mission_patch_small : string[] without success. I made this change for mapping the links URL in the getMission() method mentioned above.

export interface IMission {
  mission_name: string;
  launch_year: string;
  details: string;
  mission_patch_small: string;
  links: ILinks[];
}

export interface ILinks {
  mission_patch_small: string[];
}


This is how I fetch data using HttpClient & RxJs Observables

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { IMission } from '../models/mission';
import { Observable } from 'rxjs';
@Injectable({
  providedIn: 'root',
})
export class SpacexapiService {
  baseURL: string = 'https://api.spacexdata.com/v3/launches';
  constructor(private http: HttpClient) {}

  getMission(): Observable<IMission[]> {
    return this.http.get<IMission[]>(this.baseURL);
  }

  

}

This snippet shows my missionList.component.ts file

import { Component, OnInit } from '@angular/core';
import { IMission } from '../models/mission';
import { SpacexapiService } from '../network/spacexapi.service';
@Component({
  selector: 'app-missionlist',
  templateUrl: './missionlist.component.html',
  styleUrls: ['./missionlist.component.css'],
})
export class MissionlistComponent implements OnInit {
  missionList!: IMission[];
  selectedMission!: IMission;
 

  constructor(private service: SpacexapiService) {}

  getMission(): void {
    this.service.getMission().subscribe((resp: any) => {
      this.missionList = resp;
      console.log(resp);
    });
  }

  onSelect(mission: IMission): void {
    this.selectedMission = mission;
  }

  ngOnInit(): void {
    this.getMission();
  }
}

Data Displayed in The Parent Component missionList

This section works fine: The nested data from links displays without issues here

<ul class="missions" 
 
*ngIf="missionList">
    <li *ngFor="let mission of missionList | keys"   
(click)="onSelect(mission)"  
<span>{{mission.mission_name}}</span> -- {{mission.launch_year}}
        <p>{{mission.details}}</p>
        <aside><img [src]="mission?.links?.mission_patch_small" /></aside>
    </li>
</ul>

<app-missiondetails>[mission]="selectedMission"></app-missiondetails>

Keys Pipe

export class KeysPipe implements PipeTransform {
  transform(value: any, args?: any[]): any {
    let keys: any = Object.keys(value),
      data: any = [];
    keys.forEach((key: any) => {
      data.push(value[key]);
    });
    return data;
  }

Child Component missionDetails


export class MissiondetailsComponent implements OnInit {
  @Input() mission!: IMission;
  constructor() {}
  ngOnInit(): void {}
}

Finally, Here's How I Attempt to Display Data in the Child and Encounter the Error.

<ul *ngIf="mission">
    <li><span>{{mission.mission_name}}</span> {{mission.launch_year}}
        <p>{{mission.details}}</p>
        <p>{{mission.links | json}}</p>
        <aside><img [src]="mission?.links?.mission_small_patch" /></aside>
    </li>
</ul>


Answer №1

Take a closer look at the object you received, consider the following details...

"links": {
      "mission_patch": "https://images2.imgbox.com/40/e3/GypSkayF_o.png",
      "mission_patch_small": "https://images2.imgbox.com/3c/0e/T8iJcSN3_o.png",
      "reddit_campaign": null,
      "reddit_launch": null,
      "reddit_recovery": null,
      "reddit_media": null,
      "presskit": null,
      "article_link": "https://www.space.com/2196-spacex-inaugural-falcon-1-rocket-lost-launch.html",
      "wikipedia": "https://en.wikipedia.org/wiki/DemoSat",
      "video_link": "https://www.youtube.com/watch?v=0a_00nJ_Y88",
      "youtube_id": "0a_00nJ_Y88",
      "flickr_images": []
    },

In your interface, you have mentioned links: ILinks[]; suggesting that links is an array, however, from the object you received, links is actually an object.

To fix this issue, start by changing this to links: ILinks;

Another thing to pay attention to is the property names...

In your interface, you define mission_small_patch but in the properties, it's called mission_patch_small. Aligning these will resolve your problem

Check out this link for more information

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

Creating a unique XML structure using JQuery Ajax POST for a customized Filter Chain

I would like to send an XML structure via AJAX in order to receive a filtered result set. The webservice is capable of handling POST requests, but I am encountering some issues with my POSTing method. $.ajax({ url: ajaxurl, data: { inputxm ...

Is it possible to incorporate an element using absolute positioning using jQuery or Javascript?

When trying to add a new element on the screen, I am facing an issue with the absolute positioning not working properly. Sample Code in Javascript function drawElement(e,name){ $("#canvas").append("<div id='" + name + "' class='e ...

Using the hover event in a jQuery plugin: A step-by-step guide

A star rating plugin I am developing is encountering an issue with implementing the hover event. jquery, (function($){ $.fn.extend({ rater: function(options) { var defaults = { } var options = $.exten ...

Swap out function with jquery

Here is a snippet of code that I need help transforming into jQuery: txtName.value = txtName.value.replace(/(\r?\n){2,}/, '\n').replace(/^\r?\n|\r?\n$/, ''); txtURL.value = txtURL.value.replace(/(&bs ...

After refreshing the page, waypoints will no longer activate beyond the specified element

When I set the option triggerOnce to true, it works perfectly if I start scrolling from the top of the page and scroll down. However, if I refresh the page at the bottom and start scrolling up, it doesn't trigger the targeted element above like it di ...

Modify a JavaScript object in JSON format using another object as reference

Consider two JSON formatted JavaScript objects: obj1 = { prop1: 1, prop2: 2, prop3: 3 } obj2 = { prop1: 1, prop2: 3 } In the context of jQuery or Angular, what is the recommended practice to update obj2 into obj1 while also re ...

Inadequate tweening adjustments upon mouse exit

When I try to tween a variable down to zero on mouseleave, nothing seems to happen when the mouse leaves the container. I've experimented with different approaches but can't figure out what I'm doing wrong. Here's the code snippet in q ...

Having trouble with Node.js multiparty upload functionality

I'm facing an issue with the functionality of multiparty.Form(). Specifically, I am attempting to print numbers like 2, 3, and 4. Below is the code snippet for uploading images: app.post('/gallery/add',function(req, res,next) { var input = ...

How can you use JavaScript to iterate through every object using a for loop?

I'm trying to determine if a button is clickable based on certain requirements, but I can't seem to get the initial function to work. Within this object array, each object represents a button with specific requirements. For example, the "story" ...

Implement deferred loading of Stripe <script> in components using ElementRef

Does anyone know a way to lazy load a section of a website that uses Stripe for payment? I don't want to include the <script> tags in the index.html file since it may not always be used and could just add unnecessary bandwidth. I came across th ...

Printing images from JSON using jQuery

Attempting to implement the following: $.each(json, function(i, mhs) { $('<tr/>', { html: [$('<td/>', { text: mhs.nim }), $('<td/>', { text: mhs.nama }), $(& ...

Save all the text file lines into an array while getting rid of any instances of

Looking for a way to replicate the functionality of this python code using javascript and Jquery: config_array = open("config.txt").read().splitlines() This snippet reads the "config.txt" file, splits each line into an array element, and removes the &apo ...

Looking for a way to make this HTML tab appear using ng-show and an external variable in AngularJS - seeking guidance as a beginner!

Here is the HTML code snippet controlling the tab presentation: <li class="presentation" ng-show="currentUserAuthority == LIBRARIAN" > However, there seems to be an issue with the variable "currentUserAuthority" not updating until after the web pag ...

Running Protractor tests with 'directConnect: true' causes the ERROR:browser_switcher_service.cc(238)] XXX Init() to be thrown

While running Protractor tests with directConnect: true, I am encountering an error as soon as the browser window appears. Interestingly, the test continues to run smoothly without any apparent issues. However, when I switch to Firefox or use seleniumAddr ...

Transferring information from a service to a controller in AngularJS version 1.3.15

I am facing a major issue in sending data from my StartingWebGazer service to WorkspaceController.js. The startingWebGazer service utilizes webgazer.js to evaluate prediction points, which are then passed to the xprediction and yprediction variables within ...

Is there a way to customize the color of a React component from a different source?

I am currently utilizing a React component library called vertical-timeline-component-react. <Fragment> <Timeline> <Content> <ContentYear startMonth="12" monthType="t ...

Filtering JSON data in Ionic 4 based on multiple values

Recently, I've encountered an issue with filtering a local JSON file based on multiple criteria. Initially, I thought that combining conditions using '&&' would solve the problem. However, when the data is loaded into Ngx-Datatable, nothing ...

Firebase causing API to render only upon typing initiation

I have been working on developing a Twitter-like app using React and Firebase, but I have come across a small bug. Currently, I am using useEffect to display my firebase collection when the page loads, and then mapping the tweets to the page. However, the ...

Tips for setting a variable using useState() and useEffect() with an asynchronous database call

I have a scenario where I am attempting to set a variable by making a simple GET request to the database. The issue I am facing is that even though the database call is returning the data correctly, the variable remains undefined after each re-render. Belo ...

What steps can I take to implement a functional 'echo' command within a Jquery terminal?

Trying to create an echo command that displays what the user types in a JQuery terminal. Here is the code snippet: <link href="https://unpkg.com/jquery.terminal/css/jquery.terminal.min.css" rel="stylesheet" /> <script src="https://cdnjs.clou ...