这是Angular项目中我的服务层的一部分。为什么console.log
未定义count
?我只能访问订户功能中的值。我想在BehaviorSubject中使用count;我怎么能在那里访问它?
export class DataService {
public count;
private baskets;
constructor(private _store: StoreService) {
this._store.reviewBasketProduct().subscribe(data => {
this.baskets = data;
//console.log(data.len)
this.count = this.baskets.length;
})
console.log('aa' + this.count)
}
private messageSource = new BehaviorSubject<number>(this.count);
currentMessage = this.messageSource.asObservable();
}
答案 0 :(得分:2)
您需要在订阅中编写控制台,因为控制台在reviewBasketProduct订阅之前执行。
import { OnInit } from '@angular/core';
export class DataService implements OnInit {
public count;
private baskets;
private messageSource;
constructor(private _store: StoreService) {
this._store.reviewBasketProduct().subscribe(data => {
this.baskets = data;
//console.log(data.len)
this.count = this.baskets.length;
console.log('aa' + this.count);
});
};
ngOnInit() {
this.messageSource = new BehaviorSubject < number > (this.count);
currentMessage = this.messageSource.asObservable();
}
}