Exploring ways to interact with an API using arrays through interfaces in Angular CLI

I am currently utilizing Angular 7 and I have a REST API that provides the following data:

{"Plate":"MIN123","Certifications":[{"File":"KIO","Date":"12-02-2018","Number":1},{"File":"KIO","Date":"12-02-2018","Number":1},{"File":"preventive","StartDate":"06-02-2018","EndDate":"12-02-2018","Number":2},{"File":"preventive","StartDate":"06-02-2019","EndDate":"25-03-2019","Number":2}],"Locations":[{"place":"start","Date":"12-02-2018","Address":"Cra 99 No.69A 81"},{"place":"end","Date":"12-02-2018","Address":"Cra 89 No.69A 81"}],"Issues":[{"place":"end","Date":"12-02-2018","Address":"Cra 89 No.69A 81","Description":"Not reporting"}],"id":"5c7c990de5b1660fb032dc8b"}

accessible through this link: "http://localhost:3000/api/Cars/5c7c990de5b1660fb032dc8b". In my Angular application, it is structured in the following manner:

My service

//data-api.service.ts
import { Injectable } from '@angular/core'; 
import {HttpClient,HttpResponse, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/internal/Observable' ;
import { map } from 'rxjs/operators';
import { VehicleInterface } from '../Model/vehicle-interface';

@Injectable({
    providedIn: 'root'
})
export class DataAPIService {
    vehicles: Observable<any>;
    vehicle: Observable<any>;
    constructor(private http:HttpClient) { }

    getVehicleByID(id: string){
     const url_api = `http://localhost:3000/api/Cars/${id}`;
     this.vehicle=this.http.get(url_api);
     console.log(this.vehicle);
     return (this.vehicle);
    } 
}

Based on my research regarding interfaces, here are my interface definitions:

Certifications

//certifications-interface.ts
export interface certificationsInterface{
    File ?: string;
    Date ?: string;
    Number ?: number;
}

Disadvantages

//issues-interface.ts
export interface issuesInterface{
    place ?: string;
    Date ?: string;
    address ?: string;
    Description?:string;
}

Locations

//locations-interface.ts
export interface locationsInterface{
    place ?: string;
    Date ?: string;
    address ?: string;
}

Vehicles

//vehicle-interface.ts
import {certificationsInterface} from "./certifications-interface";
import {issuesInterface}from "./issues-interface";
import {locationsInterface}from "./locations-interface";

export interface VehicleInterface{
    Plate ?: string;
    Status ?: number;
    Certifications ?:certificationsInterface[];
    Issues ?: issuesInterface[];
    Locations ?: locationsInterface[];
}

Currently, I intend to display this information via the console before incorporating it into the HTML. To achieve this, I'm implementing my component as follows:

//vehicle-details.component.ts
import { Component, OnInit } from '@angular/core';
import { DataAPIService } from 'src/app/Services/data-api.service';
import { ActivatedRoute,Params } from '@angular/router';
import { VehicleInterface } from 'src/app/Model/vehicle-interface';

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

  constructor(private dataAPI:DataAPIService,private route: ActivatedRoute) { }
  
  private vehicle: VehicleInterface={
    Plate :'',
    Status :null,
    Certifications:null,
    Issues:null,
    Locations:null
  }
  
  ngOnInit() {
    const vehicleID=this.route.snapshot.params['id'];
    this.getDetails(vehicleID);
    console.log(this.vehicle);
  }

  getDetails(id:string){
    this.dataAPI.getVehicleByID(id)
      .subscribe(vehicle => this.vehicle = vehicle);
      console.log(this.vehicle);
  }

}

The output currently displays an empty object. I suspect the issue may lie in how the component handles the data retrieval. I've provided as much detail about my problem as possible, and I would appreciate any assistance you can provide.

Answer №1

When using your method getVehiculoByID as an observable, it's important to remember that when you log this.vehiculo, it may not have resolved yet. To ensure that you are logging the correct value, try moving your console.log(this.vehiculo) statement after the assignment like this:

this.dataAPI.getVehiculoByID(id)
      .subscribe(vehiculo => {
           this.vehiculo = vehiculo;
           console.log(this.vehiculo);
      });

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 steps should I take to resolve issues with importing Angular modules?

Success! import { MatInputModule } from '@angular/material/input' import { MatSelectModule } from '@angular/material/select' Having Issues import { MatInputModule, MatSelectModule } from '@angular/material' What could be c ...

Clicking on the <Link to=URL> in a React application built with Typescript and Redux triggers the disappearance of the component

Issue Background The application was created using npx create-react-app rrts --typescript, which sets up React, Redux, and Typescript. Problem Visualization (Content is the component with sentences) View Problem Image Here Problem Description Clicking o ...

reposition content according to screen size

In my web development project, I am utilizing both bootstrap and angular to create a component that includes a menu feature. My goal is to have the menu displayed in the navbar when the screen size is large, but switch it to a dropdown menu on smaller scr ...

Optimizing your data layer in Angular2: A Guide to Best Practices

As a newcomer to Angular2, I am diving into hands-on learning. My current project involves building multiple views with parent components, child components, and database services. After successfully creating one view, I am now gearing up to implement other ...

Tips for mocking the router.navigate function in Jest

As a newcomer to unit testing with Jest in Angular, I find myself facing a challenge when it comes to testing components that utilize the this.router.navigate() method. Previously, I used Jasmine for testing and followed these steps: import { Router } from ...

Essential parameters needed in a Typescript function signature

My code includes the following type definition: type FuncWithRequiredParams = (a: number, b: number, c:string) => void const func1: FuncWithRequiredParams = (a: number, b: number, c: string) => {} // This is functional const func2: FuncWithRequiredP ...

How can the `!` operator be utilized in MikroORM Typescript entities?

How can I declare a key in a JS object with an ! before the colon? MikroORM syntax for class @Entity() export class Post { // Using @PrimaryKey() decorator to designate primary key @PrimaryKey() id!: number; @Property({ type: "date", de ...

Issue occurred with Firebase geoFire setting: unable to access properties of undefined when reading 'pieceNum_'

Recently, I decided to update my old Ionic Angular app and upgraded the firebase module to version 9.23.0 along with the geofire module to version 6.0.0. However, upon calling the set function on geoFire with an id and an array of coordinates, I encountere ...

The 'mergeMap' property is not found on the 'Observable<any>' type

Currently, I'm working on an HttpInterceptor within my Ionic 4 application. My goal is to retrieve the Bearer Authorization token stored in local storage. Although I attempted to utilize mergeMap for this task, I kept encountering the following error ...

Ways to reverse bypassSecurityTrustHtml and convert SafeValue to a string

When I generate HTML and insert it into my webpage, I use the following code: let data = '<font color=blue>hello world</font>'; this.safevalue = this.domSanitizer.bypassSecurityTrustHtml(data); In another part of my code, I needed t ...

Tips on efficiently adding and removing elements in an array at specific positions, all the while adjusting the positions accordingly

My challenge involves an array of objects each containing a position property, as well as other properties. It looks something like this: [{position: 1, ...otherProperties}, ...otherObjects] On the frontend, these objects are displayed and sorted based on ...

Looking to customize the scrollbar style within an Angular Material table?

Is there a standard method for customizing the scrollbar design in an Angular Material table similar to the one displayed below? (I am unable to identify any applicable styling attributes through element inspection.) angular-table-issue ...

What is the best way to display "No results found" in Mat-select-autocomplete?

I am working with the mat-select-autocomplete for a multiselect dropdown. When searching for values that are not in the list, I want to display a message saying "No results found". Can someone please help me achieve this? Link to Code ...

Having difficulties generating ngc and tsc AOT ES5 compatible code

I've explored various options before seeking help here. I have an angular2 library that has been AOT compiled using ngc. Currently, I am not using webpack and solely relying on plain npm scripts. Below is the tsconfig file being utilized: { "comp ...

Retrieving Values from Components in Angular 6

Encountering an issue while retrieving values from different components. The scenario involves 2 components - ReceiveBookingManageComponent as the first component and DriverTablePickerComponent as the second one. The problem arises in DriverTablePickerCo ...

What is the best way to conduct tests on Typescript modules that are not intended for

Even though the compiler accepts my current solution without any errors, the tests are still failing with the message "ReferenceError: myFunction is not defined". I am interested in testing the functionality of the following module using TypeScript: File1 ...

Imitate a targeted ngxs store selection using ngxs

Within this component, there are two ngxs selectors being utilized: @Component({ selector: 'some-component', templateUrl: './some-component.html', styleUrls: ['./some-component.scss'], changeDetection: ChangeDetectionS ...

Conceal the Froala editor when blur events occur

Currently, I am utilizing Forala with the specific setting: initOnClick: true, Everything is running smoothly, but is there a way to accomplish the "opposite" I'm looking to hide the editor upon blur? I have searched through the documentation, but d ...

Vuefire encountering an issue with Vue 3 and throwing a Vue.use error

After setting up a Vue app and importing Vue from the vue module, I encountered an issue: ERROR in src/main.ts:4:5 TS2339: Property 'use' does not exist on type 'typeof import("/data/data/com.termux/files/home/ishankbg.tech/node_modules/vue/ ...

Remove validators from an Angular formArray

Is there a way to reset validators for the formArray within my formGroup? Check out my StackBlitz for reference. .ts this.createEstimation = this.fb.group({ name: ['', Validators.required], surname: ['', Validators.required], ca ...