简体   繁体   English

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

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

I have a service which has an observable which is subscribed to. 我有一个已订阅的可观察的服务。 The payload is passed onto a subject in the service. 有效负载被传递到服务中的主题上。 However, when I subscribe to the subject in my component, nothing is happening. 但是,当我在组件中订阅该主题时,没有任何反应。 I should see the console.log in the .subscribe method in the ngOnInit in the component. 我应该在组件中ngOnInit.subscribe方法中看到console.log

I had this same setup working with a previous version which subscribed to an observable resulting from a http.get operation. 我在以前的版本中使用了相同的设置,该版本订阅了http.get操作产生的可观察结果。 I want to know why its not working with this version. 我想知道为什么它不适用于该版本。

The service: 服务:

@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.
   }

}

The component.ts: 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;
    });
  }

}

Like Ringo said, the component most likely subscribes after data has been passed (via .next()) to the availableTiles$ Subject. 就像Ringo所说的那样,组件很可能在数据(通过.next())传递给availableTiles $主题之后进行订阅。

Seeing as you're using Subject, late subscribers won't receive a value until .next() has been called on the source Subject again. 看到您正在使用Subject,直到在源Subject上再次调用.next(),以后的订阅者才会收到值。

One solution is to use BehaviorSubject. 一种解决方案是使用BehaviorSubject。 This means that any subscriber (including late ones) will immediately receive a value. 这意味着任何订户(包括后期订户)都将立即获得价值。

@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