Getting the Most Out of .find() in Angular 4

Despite reading various similar questions, I'm still struggling to make the .find() function work in my application.

I have a service with the following API:

export class VehicleService {
  private defUrl = 'API';

  constructor(private http: Http) { }

  getVehicleByVehicleId(vehicleid?: any) {
    const url = (!vehicleid) ? this.defUrl : 'API1&vehicle_id=' + vehicleid;
    return this.http.get(url)
      .map(res => res.json());
  }


    searchVehicleId(description?: string) {
    const url = (!description) ? this.defUrl : 'API2&description=' + description;
    return this.http.get(url)
      .map(res => res.json().vehicles);
  }
}

Component

export class VehicleComponent implements OnInit {

  ngOnInit() {

    this.searchQuery = new FormGroup({
      vehicleDescription: new FormControl('', Validators.required)
    });
  }


  constructor(private vehicleService: VehicleService) { }

  public fleet: Fleet[];
  public description: Description[];
  public searchQuery: FormGroup;
  public searchVehicleId: any;


  public searchByVehicleId(searchQuery) {
    this.vehicleService
      .searchVehicleId(searchQuery.value.vehicleDescription)
      .subscribe(searchQuery => {
        this.description = searchQuery;
        this.searchVehicleId = this.description.find() // <= HOW TO IMPLEMENT THIS?
    this.vehicleService
      .getVehicleByVehicleId(this.searchVehicleId)
      .subscribe(searchQuery => {
        this.vehicle = searchQuery;
      })
      });
  }
interface Vehicle {
  status: number;
  dallases: Vehicle[];
}

interface VehicleDetails {
  vehicle_id: number;
  dallassettings: string;
  dallasupdated: string;
  dallas_list: DallasList[];
}

interface DallasList {
  number: number;
  auth: number;
}

//////////////////////////////////
//////////////////////////////////

interface Description {
  vehicles: DescriptionDetails[];
}

interface DescriptionDetails {
  id: number;
  custom_description: string;
  description: string;
}

API2

{
    "vehicles": [{
        "description": "SKODA ROOMSTER",
        "id": 123456,
        "custom_description": ""
    }, {
        "description": "SKODA ROOMSTER",
        "id": 123456789,
        "custom_description": ""
    }]
}

My approach involves passing the description from the FormGroup - specifically the vehicleDescription field - to the searchByVehicleId method. The goal is to find the id corresponding to the provided description value (from the 'description' field in API2). Once we locate the id, it is used further in

this.vehicleService.getVehicleByVehicleId
...

The main challenge lies in my lack of understanding on how to correctly implement the .find() method.

Thank you

Answer №1

References from the MDN documentation:

In this code snippet, we are searching for a specific vehicle ID within the 'description' array by using the Array.find() method.

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

It seems that Angular2 Universal is experiencing some instability as it crashes frequently with the message "[nodemon] app crashed - waiting for file

After trying to work with the starter repo from my Angular class, I've found it to be quite unstable. It seems to be working locally when hitting the same service as remote, but I keep encountering errors. I have followed all the instructions: npm r ...

Testing the mirkoORM entities at a unit level

Trying to perform a unit test on a method within a MikroORM entity, I am attempting to populate a mikroORM collection field with test data. Specifically, I am using jest for this task: describe('Team Tests', () => { it('isLeader shoul ...

Angular2 Event:keyup triggers the input to lose focus

I am working on a component with an input element that is bound to a property. I want the input field to update in real time as I type in it. Here is my current code: <input type="text" #updatetext [value]="item.name" (keyup)="updateItem(item.$key, up ...

Fastest method to invoke a potentially undefined function

With a background in C#, I am familiar with the null-conditional operator which allows you to call a function while avoiding a potential null-reference exception like this: Func<int> someFunc = null; int? someInteger = someFunc?.Invoke(); // someInte ...

Issue with resolving symbol JSON in Angular 7 when using JSON.stringify

Let me start off by saying that I am new to Angular 7. Currently, I am in the process of developing an application using Angular 7 with a C# backend. The specific challenge I am facing is the need to serialize an object in my component/service before sendi ...

Ways to change the CSS styling of the placeholder attribute within a textarea or input field tag

I am currently working on adjusting the font size of the text within the placeholder attribute of a textarea element. While I have been successful in achieving this using vanilla CSS, I have encountered difficulties when trying to implement the same concep ...

Retrieve information from a URL to transmit to a different page in NextJS using Typescript and AppRouter

I'm struggling with transitioning from the Home page to the Detail page. I've successfully passed data to the URL from the Home screen, but I'm having trouble accessing it in the Detail screen. I'm working with NextJS ver 13, using Type ...

Exploring the power of TypeScript for authenticating sessions with NextJS

Utilizing next-auth's getSession function in API routes looks something like this for me: const mySession = await getSession({ req }); I have confirmed that the type of the mySession is outlined as follows: type SessionType = { user: { email: s ...

The Type X is lacking essential properties found in Type Y, including length, pop, push, concat, and an additional 26 more properties. Code: [2740]

One interesting thing I have noticed is the Product interface: export interface Product{ code: string; description: string; type: string; } There is a service with a method that calls the product endpoint: public getProducts(): Observable<Product ...

` Detecting initialized properties of classes using Eslint rule`

When useDefineForClassFields:true is used, the code below becomes invalid when targeting es2022: Cannot read properties of undefined (reading 'array') class Bar { array = new Array(); } class Foo { foo = this.bar.array; // Property &apo ...

What is the best way to clear a form in a Next.js 13.4 component following a server action?

Currently, I am working on a component using next.js 13.4, typescript, and resend functionality. My code is functioning properly without clearing data from inputs, as it uses the "action" attribute which is commented out. However, I started incorporating ...

Troubleshooting Electron Angular Application Connectivity Issues with API

While developing my ionic/angular app as an electron app, I encountered a problem when running it. After loading, I received the error message shown below: Refused to connect to 'https://xxxxxxxxxx.com/whpacking/v1/getlocations' because it violat ...

"Typescript with React and Material-UI Table - A seamless user experience with no errors

I have been working on incorporating the "material-table" library into my TypeScript and React project, but I am facing an issue where the page appears blank without any compiling errors. Environment configuration: npm: 6.11.3 nodejs: 10.17.0 typescript: ...

The attribute 'getValue' is not a valid property for the data type 'Subject<boolean>'

Currently, I am working with Angular2 and have a BehaviorSubject. isOpen$: Subject<boolean> = new BehaviorSubject<boolean>(true); When I try to retrieve the latest value using: isOpen$.getValue() It functions correctly, however, there is a ...

Using TypeScript to incorporate JS web assembly into your project

I have been attempting to incorporate wasm-clingo into my TypeScript React project. I tried creating my own .d.ts file for the project: // wasm-clingo.d.ts declare module 'wasm-clingo' { export const Module: any; } and importing it like this: ...

Encountered an issue in React and Typescript where the argument type is not compatible with the parameter type 'EventListenerOrEventListenerObject'

One challenge I am facing is integrating Typescript into my React project: componentDidMount() { document.addEventListener('mousemove', this.handleMouseMove); } private handleMouseMove = (e: React.MouseEvent<HTMLElement>) => { appS ...

Fetching HTML files directly after building Angular (Tips for Developing Chrome Extensions)

Currently, I am in the process of creating a custom Panel within Chrome DevTools using Angular and Typescript. Through my efforts, I have successfully implemented a new Panel by utilizing the code snippet provided below: chrome.devtools.panels.create(&ap ...

leveraging parcel for importing typescript dependencies

I am currently using parcel to process typescript for a web extension. I have installed JQuery and its type definitions via npm. In my typescript file, I have the following at the top: import $ from "jquery"; import "bootstrap"; However, when running run ...

The retrieval of cookies from the Response object is not possible with Typescript

While working on my google chrome extension, I implemented a post call that looks like this: public someapiCall(username: string, password: string) { var url = 'http://test.someTestServer.com/api/user/someApiCall'; let headers = new Hea ...

Iterate through controls to confirm the accuracy of the password输入 unique

Struggling a bit here since ControlGroup is no longer available. I need to ensure that two passwords match on the front end. this.updatePassordForm = _form.group({ matchingPassword: _form.group({ password: new FormControl('' ...