IONIC 5:将事件更改为可观察的问题

IONIC 5: Issues in changing Events to Observable

自从 Ionic 5 出来后,我就决定尝试一下。 我了解到他们现在使用 Oberservables 而不是事件。 我的代码中有以下事件:

在我的构造函数中这样订阅:

                this.events.subscribe('go-to-slide', (tab, id) => {
  this.currentID = id;
  if (id === 0) {
    this.showLeftButton = false;
  }
  // if data has already been loaded
  if (this.dataLoadedFlag === true) {
    // from tile
    if (this.globalVariableService.comesFromTileClick === true) {
      if (this.globalVariableService.languageChanged === true) {
        this.languageChanged = false;
        this.slidesComponent.slides.slideTo(id, 0);
        this.getSectorTitlesAndColours();
        this.dataLoadedFlag = true;
        this.updateHeader(id);
      } else if (this.globalVariableService.languageChanged === false) {
        this.updateHeader(id);
      }
    } else if (this.globalVariableService.comesFromTileClick === false) {

    }
  } else if (this.dataLoadedFlag === false) {

    if (this.globalVariableService.comesFromTileClick === true) {
      this.slidesComponent.slides.slideTo(id, 0);
      this.getSectorTitlesAndColours();
      this.dataLoadedFlag = true;
      this.updateHeader(id);
    } else if (this.globalVariableService.comesFromTileClick === false) {
      this.getSectorTitlesAndColours();
      this.showRightButton = true;
      this.dataLoadedFlag = true;
      this.updateHeader(0);
    }
  }
  const tempGlobalVariableService = this.globalVariableService;
  // tslint:disable-next-line: only-arrow-functions
  setTimeout(function() {
    tempGlobalVariableService.comesFromTileClick = false;
  }, 500);
});
}

并在不同 components/methods 中发布这样的事件:

this.events.publish('go-to-slide', 1, 1);

我尝试了不同的方法来将此代码更改为可观察的,但我似乎找不到正确的方法。

有人试过这个可以帮助我吗? 谢谢

我已经在这里回答了

您可以为此创建一个小型服务:

import {Injectable} from '@angular/core';
import {Subject} from 'rxjs';

@Injectable({
    providedIn: 'root'
})
export class GlobalFooService {

    private fooSubject = new Subject<any>();

    publishSomeData(data: any) {
        this.fooSubject.next(data);
    }

    getObservable(): Subject<any> {
        return this.fooSubject;
    }
}

完整示例请参考其他回答

顺便说一句,讨论这个评论:

I have learned that they are now using Oberservables instead of Events

事实并非如此。基本上,他们已经从 Ionic 5 中删除了 Events 服务,并要求我们通过创建我们自己的类似实现来使用 Observables 代替。

他们可能从 Ionic 3 开始就在内部使用 Events。但是从 Ionic 4that 开始,他们已经删除了内部使用,因为 Obersables 已经发展得如此之快,这对两者来说都是一种 backbone Angular & 离子。