我有一个服务,它有一个可订阅的观察者。有效负载传递给服务中的主题。但是,当我订阅我的组件中的主题时,没有任何事情发生。我应该在组件中console.log
的{{1}}方法中看到.subscribe
。
我有同样的设置使用以前的版本,该版本订阅了由http.get操作产生的可观察量。我想知道为什么它不能使用这个版本。
服务:
ngOnInit
component.ts:
@Injectable()
export class TileService {
availableTiles$ = new Subject<any>();
// The view is expecing an array, else: Error trying to diff '[object Object]'. Only arrays and iterables are allowed
source: {}[] = [
{title: 'Title A'},
{title: 'Title B'}
];
simpleObservable = new Observable((observer) => {
observer.next(this.source);
observer.complete();
});
constructor() { }
getTiles(): void {
this.simpleObservable.subscribe(x => this.availableTilesStream(x));
}
availableTilesStream(data) {
console.log(data); // Logs an array of the two objects from the source array
this.availableTiles$.next(data); // Nothing seems to happen here.
}
}
答案 0 :(得分:5)
与Ringo一样,在将数据传递(通过.next())到availableTiles $ Subject之后,组件最有可能订阅。
当您正在使用主题时,迟到的订阅者将再次收到一个值,直到再次在源主题上调用.next()。
一种解决方案是使用BehaviorSubject。这意味着任何订户(包括迟到的订户)都会立即收到一个值。
@Injectable()
export class TileService {
availableTiles$ = new BehaviorSubject<any>([]); // must be initialised with a value