如果我在打字稿中调用 Array.find() 则订阅函数不会调用

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

我对 Typescript 和 Web 开发真的很陌生。当我订阅一个事件但找不到解决方案时,我发现了一件奇怪的事情。 我有一个带有 BehaviorSubject 的服务,其中包含一个 carId。我有一个页面,其中有一个 ID 列表,如果我单击一个 ID,它就会调用 setCarId。到目前为止一切正常。

这是服务:

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

我还有另一项服务,我订阅 carId 上的更改。在这里,我有一个汽车对象,我想从我的汽车数组中获取那辆车,其 ID 在我的 BehaviorSubject 中。我得到了我需要的汽车,就像我的代码中的 array.find 方法一样,它工作正常,但不是用于订阅。我不知道为什么,但是使用 this.car = this.cars.find(car => car.carId == carId) 这一行,订阅方法不会被调用,但如果没有那一行,它就可以正常工作。

@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

我不知道为什么会这样,也不知道如何解决,所以请帮助我。

订阅工作正常,但您的代码中存在一些问题。

首先,汽车列表未定义,因此它不会在您的列表中找到汽车。

其次,您尝试在 this.subscription 上调用 getCarId 方法,但 this.discription 没有该方法,CarService 有。

如果您像这样在 MyService 中初始化您的汽车数组,它将正常工作。

@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) 
        });
    }
}

我得到了解决方案。我不知道为什么,但是在订阅方法中我不能使用数组的任何方法,所以例如 console.log(this.cars.length) 也没有用,不仅仅是 this.cars.find.但是 console.log(this.cars) 正确写出数组。无论如何,解决方案是我像这里一样用一个空数组初始化汽车数组。

 cars:Array<Car>=[];

之后一切正常。如果有人能向我解释其中的原因,那就太好了,感谢您的所有帮助。 :)