Search code examples
angulartypescriptrxjssubscriptionbehaviorsubject

Subscribe function not call if I call Array.find() in it in typescript


I am really new to Typescript and web development. I'm finding a strange thing when I subscribe to an event and cannot find solution for it. I have a service with a BehaviorSubject which holds a carId in it. I have a page where there is a list of ids, and if I click on an id, then it calls setCarId. So far everything is working fine.

This is the service:

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

And I have another service, where I subscribe to changes on carId. In this I have a car object and I want to get that car from my array of cars for which the id is in my BehaviorSubject. I get the car that I need, with an array.find method like in my code, and it's working properly, BUT NOT for subscribe. I don't know why, but with this line this.car = this.cars.find(car => car.carId == carId) the subscribe method doesn't get called, but without that line it works properly.

@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 don't know how why this is happening and how to solve it, so please help me.


Solution

  • I got the solution. I don't know the reason of why, but in subscribe method I couldn't use any methods of array, so for example console.log(this.cars.length) also didn't work, not just this.cars.find. However console.log(this.cars) write out correctly the array. Anyway the solution is that I initialized the cars array with an empty array like here.

     cars:Array<Car>=[];
    

    and after this everything worked correctly. If someone can explain me the reason of this, that would be great and thank you all of your helps. :)