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.