0

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

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

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

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

有人已经尝试过这个并且可以帮助我吗?谢谢

4

1 回答 1

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

这不是真的。基本上,他们已经Events从 Ionic 5 中删除了该服务,并要求我们Observables通过创建我们自己的类似实现来使用它。

他们可能Events从 Ionic 3 开始就一直在内部使用。但是从 Ionic 4 开始,他们已经删除了内部使用,因为 Obersables 已经发展得如此之多,并且它是 Angular 和 Ionic 的一种支柱。

于 2020-02-17T06:40:11.880 回答