【发布时间】:2018-04-24 21:30:06
【问题描述】:
我有一个订阅了 observable 的服务。有效负载被传递到服务中的主题。但是,当我在组件中订阅主题时,什么都没有发生。我应该在组件的ngOnInit 中的.subscribe 方法中看到console.log。
我在以前的版本中使用了相同的设置,该版本订阅了由 http.get 操作产生的 observable。我想知道为什么它不适用于这个版本。
服务:
@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.
}
}
组件.ts:
@Component({
selector: 'app-available-tiles',
templateUrl: './available-tiles.component.html',
styleUrls: ['./available-tiles.component.css']
})
export class AvailableTilesComponent implements OnInit {
tiles: {}[];
constructor(private tileService: TileService) { }
ngOnInit() {
this.tileService.getTiles();
this.tileService.availableTiles$.subscribe(x => {
console.log('Log from availableTiles$.subscribe in ngOnInit: ', x);
this.tiles = x;
});
}
}
【问题讨论】:
-
发射发生在您订阅主题之前?除非您使用行为主题,否则任何新订阅者都不会收到发射。