0

我对 Typescript 和 Web 开发真的很陌生。当我订阅一个事件并且找不到解决方案时,我发现了一件奇怪的事情。我有一个包含 a 的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. 在这个我有一个汽车对象,我想从我的汽车数组中获取那辆车,我的BehaviorSubject. 我用我的代码中的方法得到了我需要的汽车,array.find它工作正常,但不是订阅。我不知道为什么,但是使用这一行this.car = this.cars.find(car => car.carId == carId)不会调用 subscribe 方法,但没有那行它可以正常工作。

@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

我不知道为什么会发生这种情况以及如何解决它,所以请帮助我。

4

2 回答 2

0

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

 cars:Array<Car>=[];

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

于 2017-05-03T07:16:44.210 回答
-1

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

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

其次,您尝试在 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) 
        });
    }
}
于 2017-05-02T19:34:11.317 回答