我有一个已订阅的可观察的服务。有效负载被传递到服务中的主题上。但是,当我在组件中订阅该主题时,没有任何反应。我应该在组件console.log中的.subscribe方法中 看到ngOnInit。
我在以前的版本中使用了相同的设置,该版本订阅了http.get操作产生的可观察结果。我想知道为什么它不适用于该版本。
服务:
@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.
}
}
Run Code Online (Sandbox Code Playgroud)
component.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;
});
}
}
Run Code Online (Sandbox Code Playgroud)
就像Ringo所说的那样,组件很可能在数据(通过.next())传递给availableTiles $主题之后进行订阅。
看到您正在使用Subject,直到在源Subject上再次调用.next(),以后的订阅者才会收到值。
一种解决方案是使用BehaviorSubject。这意味着任何订户(包括后期订户)都将立即获得价值。
@Injectable()
export class TileService {
availableTiles$ = new BehaviorSubject<any>([]); // must be initialised with a value
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2376 次 |
| 最近记录: |