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

时间:2020-02-17 06:34:44

标签: javascript angular events observable ionic5

自从Ionic 5问世以来,我决定尝试一下。 我了解到他们现在正在使用Oberservables而不是Event。 我的代码中包含以下事件:

在我的构造函数中订阅如下:

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

并在不同的组件/方法中发布这样的事件:

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

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

任何人都已经尝试过了,可以帮助我吗? 谢谢

1 个答案:

答案 0 :(得分:2)

我已经在这里https://stackoverflow.com/a/60246906/2405040

回答了

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

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

有关完整示例,请参阅其他答案。

顺便讨论一下此评论:

我了解到他们现在正在使用Oberservables而不是Events

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

自Ionic 3以来,他们可能一直在内部使用Events。但是自从Ionic 4以来,由于Obersables的增长如此之快,它们已经取消了内部用法,这对Angular和Ionic都是一种骨干。 >

相关问题