When using Array.find() in TypeScript, the Subscribe function does not get called

I am currently diving into Typescript and web development, but I've encountered a peculiar issue when subscribing to an event that's leaving me stumped. In my service, I'm using a BehaviorSubject to store a carId, and on a page where there's a list of ids, clicking on one triggers the setCarId function, all of which is functioning as expected.

Here's a snippet of the service:

@Injectable()
export class CarService {
   private carId = new BehaviorSubject("");
   setCarId(carId: string) {
      this.carId.next(carId);
   } 
   getCarId(): Observable<string> {
     return this.carId.asObservable();
   }

In another service, I'm subscribing to changes in the carId. Here, with an array of cars, I aim to fetch the specific car based on the id stored in the BehaviorSubject. Utilizing array.find works flawlessly for fetching the desired car properly. However, it's causing issues within the subscribe method. Strangely enough, including

this.car = this.cars.find(car => car.carId == carId)
prevents the subscribe method from being triggered, while its absence allows everything to work fine.

@Injectable()
export class MyService {

  subscription: Subscription;
  car: Car;
  cars: Array<Car>;

  constructor(private carService: CarService){
    this.subscription.getCarId().subscribe(carId=> {
       console.log('DO SOMETHING') //


       //with this row NOT working, without this row working
       this.car = this.cars.find(car => car.carId == carId) 
    });

... //MORE CODE

I'm at a loss as to why this behavior is occurring and how to address it, so any assistance would be greatly appreciated.

Answer №1

I managed to find a solution for my issue. Strangely, when working with the subscribe method, I found that I was unable to use any array methods like console.log(this.cars.length) or this.cars.find. However, when I tried using console.log(this.cars), it displayed the array correctly. To solve this problem, I initialized the cars array with an empty array as shown below.

 cars:Array<Car>=[];

After making this change, everything started functioning properly. If anyone can shed light on why this behavior occurs, I would greatly appreciate it. Thank you to everyone who offered their assistance. :)

Answer №2

Your subscription is functioning properly, however there are some issues within your code that need to be addressed.

Firstly, the list of cars is currently undefined which means it will not be able to find the car in the list.

Secondly, attempting to call the getCarId method on this.subscription is incorrect as it should be called on CarService instead of this.description.

To resolve these issues and make your code work correctly, initialize your cars array in MyService as shown below:

@Injectable()
export class MyService {

subscription: Subscription;
car: any;
cars: Array<any> = [{carId: "1"}, {carId: "2"}];

    constructor(private carService: CarService){
        this.carService.getCarId().subscribe(carId=> {
            console.log('DO SOMETHING') //

            //with this row NOT working, without this row working
            this.car = this.cars.find(car => car.carId === carId) 
        });
    }
}

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 is the best way to add all the items from an array to a div element?

I am currently facing an issue where only the last object in my array is being added to my div using the code below. How can I modify it to add all objects from the array to my div? ajaxHelper.processRequest((response: Array<Vehicle.Vehicle>) ...

Loading the value of a Subject variable in an Angular 2 application using Typescript

I am currently developing an Angular2 application where I am loading data from a service into my component as a subject. public type1Choisi: any; constructor( public formeService: FormeService, ...) { this.formeService._type1.subscribe(type1 => ...

Troubleshooting the Issue with Conditional Rendering in Nextjs & TypeScript

Struggling with rendering a component conditionally. I have a drawHelper variable and a function to toggle it between true and false. The component should render or not based on the initial value of drawHelper (false means it doesn't render, true mean ...

The problem encountered with the Enzyme mount API is a TypeError where it is unable to read the property 'find' of an undefined variable

After converting my component to a stateless one, I started encountering an error that says: TypeError: Cannot read property 'find' of undefined Previously, my tests were running smoothly before the switch. As far as I know, you can test functio ...

When passing e: EventTarget as a forwarded prop through a wrapper component, Typescript raises an error about the missing "value" property in the onChange function

In my project, there is a custom component called SelectField that serves as a wrapper for rendering label, helper text, and select input (inspired by TextField from @material-UI). The SelectField component exposes props like value and onChange, which are ...

Setting a timer in NGRX to control the interval between two actions

I am currently working with Angular and NGRX, and I have a requirement to implement a timer between two actions. The timer should start when the first action is triggered and stop when the second action occurs. I need to be able to store this timer in a gl ...

Combine both typescript and javascript files within a single Angular project

Is it feasible to include both TypeScript and JavaScript files within the same Angular project? I am working on a significant Angular project and considering migrating it to TypeScript without having to rename all files to .ts and address any resulting er ...

Harvesting Angular information using Selenium

Here is some HTML code that can be extracted using a Selenium driver: <td colspan="2"><strong>Owner</strong> <div ng-class="{'owner-overflow' : property.ownersInfo.length > 4}"> ...

SweetAlert2 not displaying properly in Ionic6 - troubleshooting the issue

My current project is an Ionic 5 Angular project with SweetAlerts2 popups. Recently, I decided to upgrade to Ionic6 and encountered an issue where the SweetAlerts2 popups are not displaying correctly. The alert seems to only show up in the header, leaving ...

What is the best way to create an Office Script autofill feature that automatically fills to the last row in Excel?

Having trouble setting up an Excel script to autofill a column only down to the final row of data, without extending further. Each table I use this script on has a different number of rows, so hardcoding the row range is not helpful. Is there a way to make ...

Encountering difficulty in retrieving value through the get method, resorting to interpolation. The value from the getTitle() method for 'this._title' is not being displayed

import { Component } from '@angular/core'; @Component({ selector: 'courses', template: '<h1>{{ getTitle() }}</h1>' ////issue with not displaying 'this._title' value??? }) export class CoursesCo ...

Using Typescript to import an npm package that lacks a definition file

I am facing an issue with an npm package (@salesforce/canvas-js-sdk) as it doesn't come with a Typescript definition file. Since I am using React, I have been using the "import from" syntax to bring in dependencies. Visual Studio is not happy about th ...

using outlines for FontAwesome icons in React Native

I am struggling to use the fontAwesome + icon in the middle of a circle as one item. I have tried placing it inside a circle icon, but it doesn't seem to work properly. import IconFA from 'react-native-vector-icons/FontAwesome'; < ...

What is the best way to remove an exported JavaScript file from Node.js?

In my Node.js library package called "OasisLib," there is a file named TypeGenerator.ts. The specific logic within the file is not crucial, but it requires access to files in the filesystem during the project build process. To achieve this, we utilized let ...

Absolute file path reference in Node.js

I'm working on a Node.js project using WebStorm IDE. Here's the structure of my project: The root folder is named "root" and inside are 2 folders: "main" and "typings". The "main" folder has a file called "foo.ts", while the "typings" folder co ...

Apache ECharts is throwing an error due to incompatible types of the 'trigger' property

I am experimenting with setting up some options in this demonstration, and here is what I have managed to achieve so far. testOptions: EChartsOption = Object.assign( {}, { backgroundColor: 'red', tooltip: { trigger: ...

Using optional chaining with TypeScript types

I'm dealing with a complex data structure that is deeply nested, and I need to reference a type within it. The issue is that this type doesn't have its own unique name or definition. Here's an example: MyQuery['system']['error ...

Importing Heroicons dynamically in Next.js for more flexibility

In my Next.js project, I decided to use heroicons but faced a challenge with dynamic imports. The current version does not support passing the icon name directly to the component, so I created my own workaround. // HeroIcon.tsx import * as SolidIcons from ...

Implementing communication between Resolvers and component methods in Angular 2+

When it comes to loading data from the backend before components are rendered, Angular suggests implementing a Resolver. Instead of creating a Resolver for each component, I am exploring a different approach where the components store the information about ...

Is it possible to implement a customized pathway for the functions within an Azure function app?

Recently, I set up a new function app on Azure using Azure Functions Core Tools with Typescript as the language. The app includes a test function named MyTestFunction that responds with an HTTP response when called. This particular function is located in ...