繁体   English   中英

Angular 5+ RxJS订阅主题不起作用

[英]Angular 5+ RxJS Subscribing to Subject Not Working

我有一个已订阅的可观察的服务。 有效负载被传递到服务中的主题上。 但是,当我在组件中订阅该主题时,没有任何反应。 我应该在组件中ngOnInit.subscribe方法中看到console.log

我在以前的版本中使用了相同的设置,该版本订阅了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.
   }

}

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;
    });
  }

}

就像Ringo所说的那样,组件很可能在数据(通过.next())传递给availableTiles $主题之后进行订阅。

看到您正在使用Subject,直到在源Subject上再次调用.next(),以后的订阅者才会收到值。

一种解决方案是使用BehaviorSubject。 这意味着任何订户(包括后期订户)都将立即获得价值。

@Injectable()
export class TileService {

   availableTiles$ = new BehaviorSubject<any>([]); // must be initialised with a value

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM