【问题标题】:Angular 5+ RxJS Subscribing to Subject Not WorkingAngular 5+ RxJS订阅主题不起作用
【发布时间】: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;
    });
  }

}

【问题讨论】:

标签: angular rxjs


【解决方案1】:

就像 Ringo 所说,组件最有可能在数据被传递(通过 .next())到 availableTiles$ Subject 之后订阅。

看到您正在使用主题,迟到的订阅者将不会收到值,直到再次对源主题调用 .next()。

一种解决方案是使用 BehaviorSubject。这意味着任何订阅者(包括迟到的订阅者)都将立即收到一个值。

@Injectable()
export class TileService {

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

【讨论】:

  • 谢谢@Ringo 和@Rich。这样可行。让我感到震惊的是,在我的http.get 版本中,我正在使用subject,并且我正在创建可观察对象并在一行上订阅所有内容,因此在我看来,可观察对象被填充然后订阅。然而,情况可能并非如此,因为即使 http.get 的目标 json 文件是本地的,订阅实际上是在填充 observable 之前发生的:this.http.get(this.tilesUrl).subscribe(tiles =&gt;{this.availableTilesStream(tiles);
  • 订阅发生在发出任何值之前。请记住,Observable 在订阅之前不会执行 - 这很重要。因此,如果您删除了该订阅,您将不会在您的开发工具中看到该 http 请求触发。
猜你喜欢
  • 2020-12-13
  • 2018-08-14
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-28
相关资源
最近更新 更多