Failure to nest interfaces in Angular when mapping JSON responses

After calling my ASP.NET Core Web API, the JSON response appears as:

[
  {
    "driver": {
      "firstName": "TEST",
      "lastName": "LAST",
      "assignedRoute": "O_ROUTE"
    }
  },
  {
    "driver": {
      "firstName": "First",
      "lastName": "Last",
      "assignedRoute": "M_ROUTE"
    }
  }
]

The TypeScript interfaces I used are as follows:

driver.ts

export interface Driver {
    firstName: string;
    lastName: string;
    assignedRoute: string;
}

schedule.ts

import { Driver } from './driver';

export interface Schedule {
    driver: Driver;
}

In schedule.service.ts:

@Injectable({
  providedIn: 'root'
})
export class ScheduleService {

  private scheduleApiUrl = 'http://localhost:55012/schedule';

  constructor(private http: HttpClient) { }

  getSchedule(): Observable<Schedule[]> {
    return this.http.get<Schedule[]>(this.scheduleApiUrl).pipe(tap(ev => console.log(ev)));
  }
}

To display the data, I subscribed to the observable in my component:

@Component({
  selector: 'app-schedule',
  templateUrl: './schedule.component.html',
  styleUrls: ['./schedule.component.css']
})
export class ScheduleComponent implements OnInit {

  schedule: Schedule[];

  constructor(private scheduleService: ScheduleService) { }

  ngOnInit(): void {
    this.scheduleService.getSchedule().subscribe(schedule => this.schedule = schedule);
    console.log(this.schedule); /* Why is it showing undefined here??? */
  }
}

I'm puzzled as to why the mapping of JSON data with a nested interface is not working. The component displays undefined for this.schedule. I've validated the JSON and it's correct. Any insights on what could be the issue? Thank you!

Answer №1

The user interface appears to be functioning properly. The variable this.commitments is assigned asynchronously, which means that by the time you try to log it in the console, it is still undefined. To resolve this issue, you should move the console.log() statement inside the subscription block.

this.commitmentsService.getCommitments().subscribe(
  commitments => {
    this.commitments = commitments;
    console.log(this.commitments);
  },
  error => {
    // It's always a good practice to handle HTTP errors
  }
);

For more information on accessing asynchronous data, refer to this link.

Answer №2

If you want to keep things simple in your component, avoid using this.commitments. Instead, opt for the async pipe:

// component
@Component({
  selector: 'app-commitments',
  templateUrl: './commitments.component.html',
  styleUrls: ['./commitments.component.css']
})
export class CommitmentsComponent implements OnInit {
  commitments$ = this.commimentsService.getCommitments();
  constructor(private commitmentsService: CommitmentsService) { }
}

//template
<some-other-component [commitments]="commitments$ | async"></some-other-component>

When I say "it makes things complicated," I'm referring to the need to manage subscriptions and ensure that this.commitments remains updated within the component. In a previous project, excessive instance variables were introduced per component just to adhere to this pattern, leading to unnecessary complexity.

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

Is it possible to transfer a JSON object from Silverlight to JavaScript?

Is it possible to pass a JSON object directly from Silverlight to JavaScript, or does it have to be serialized first? ...

Jackson: Serializing data without naming the array

This is my custom POJO for handling folder pages. public class FolderPage { private List<ApplicationIcon> applications; public List<ApplicationIcon> getApplications() { return applications; } public void setApplications(List<Applicat ...

The component prop of Typography in TypeScript does not accept MUI styling

Working with MUI in typescript and attempting to utilize styled from MUI. Encountering an error when passing the component prop to the styled component. The typescript sandbox below displays the issue - any suggestions for a workaround? https://codesandbo ...

Type of event triggered by user file upload via INPUT element

I have a piece of code that reads the contents of a locally stored file. Here is what it looks like: onFile(event: any) { console.log(event); const file = event.target.files[0]; const reader = new FileReader(); reader.onloadend = (ev: any) => { ...

The Specflow project's build was halted because of a "StackOverflowException."

Our Specflow project encountered a build failure with the error "Process is terminated due to StackOverflowException". To troubleshoot, I narrowed down the test project to just one feature file: Feature: PDBSPCTK Get Availability groups (Avgpad) - Tux Sc ...

Exploring Angular 2: The Power of HTTP Observables for Managing Asynchronous Operations. Exploring the

When working with a form that fetches data using an http observable, I encountered the need to disable the submit button while awaiting the response. Currently, I am setting the status code on each component/form to indicate running before calling the sub ...

Each time the Angular Service is called, it undergoes a reset process

For my Angular web project, I have implemented an AuthenticationGuard and an AuthenticationService to manage security. These components are from a separate branch of the project that is functioning perfectly. This is how the process should occur: Go to ...

The firebase.d.ts on iOS functions properly, whereas on Android, it becomes

Currently, I am working with Ionic 2 on my Mac system. Your system information: Cordova CLI: 6.4.0 Ionic Framework Version: 2.0.0-rc.4 Ionic CLI Version: 2.1.18 Ionic App Lib Version: 2.1.9 Ionic App Scripts Version: 1.0.0 ios-deploy version: Not instal ...

In TypeScript, the NonNullable type is like Required, but it ensures that all object properties are converted to non-

When working with TypeScript, you may have come across the Required type which transforms object properties into defined ones. For instance: interface Person { name?: string; age?: number; } Using Required<Person> will result in: interface Pe ...

What is the procedure for cancelling a file upload in the FileUpload component of PrimeNG?

1. Issue Overview Looking to terminate file upload in PrimeNG's FileUpload component when certain filename patterns are detected. Using Angular 6.0.7 and PrimeNG 6.0.2. 2. Initial Strategy 2.1. HTML Code <p-fileUpload #fileUploader name="file" ...

Remove the directory structure from the output when using grunt-concat-json

I have a scenario where my JSON files are stored in the specified path. I am looking to merge them into a single JSON file with keys matching the filename. src/ john/ doe/ one.json two.json three.json If my grunt-concat-json co ...

Trouble extracting and utilizing GraphQL queries in Typescript with relay-compiler

I attempted to utilize relay with the Typescript react starter, but I am encountering several problems. It appears that babel-plugin-relay is unable to detect the graphql statements extracted by the relay-compiler. Below is my compiler script: "relay": " ...

A guide to updating a particular row and sending parameters with jQuery and AJAX

I am utilizing a JSON response to dynamically display table content. Here is the code I am using to display row values: var rows = ''; for(var i=0; i<response.response.length; i++) { rows += '<tr><td class="country">&ap ...

Leveraging jq for uncovering shared beginnings in a JSON dataset

I have a large JSON data set containing approximately 8.7 million key value pairs retrieved from a Redis database. Each key is guaranteed to be an 8-digit number, and the value associated with each key is an alphanumeric string of 8 characters. [{ "912015 ...

Encountering a Bad Request 400 error when sending JSON data to a WCF Service through a jQuery DataTables ajax

Having trouble receiving a valid JSON response from a jQuery DataTables.Net ajax POST call to my WCF Services (4.0) service. Despite trying numerous combinations, I am unable to transfer the aoData values to my service. [Apologies for including so much co ...

eliminate any redundant use of generics

Recently, I attempted to create a pull request on GitHub by adding generics to a method call. This method passes the generically typed data to an interface that determines the return type of its methods. However, the linter started flagging an issue: ERR ...

Learn how to send an SMS using Angular and Ionic 4 without having to open the native SMS app

I have been actively monitoring the GitHub repository for the Ionic Native SMS plugin at https://github.com/cordova-sms/cordova-sms-plugin. Following the suggested configuration from the repo, I have set it up as follows: var options = { repla ...

Transform the HTTP text response into a pandas dataframe

Is there a way to utilize Python Pandas' pre-built or in-built parser to convert the text below into a pandas dataframe? Although I can create a custom parsing function, I am interested in finding out if there is a faster and ready-made solution avail ...

Utilizing Spring and JPA to Store Data in a JSON Column within a Postgres Database

My database table "test" in Postgres 9.3 has a column named "sample_column" of type json that I'm trying to populate with {"name":"Updated name"} using Spring / JPA. After researching, I found that I need to implement a custom converter to map the st ...

Verification of emails through Mailgun API by interpreting the JSON response

I'm currently working on creating an email validator using the Mailgun API, but I've hit a roadblock when it comes to parsing the JSON response. Here is the code snippet I am using: foreach (string str in this.ema.Items) { HttpWebReques ...