【问题标题】:Ionic 4 Events not working in device but working on browserIonic 4 事件在设备中不起作用但在浏览器中起作用
【发布时间】:2020-09-28 04:28:46
【问题描述】:

我正在使用"@ionic/angular": "^4.11.10"

我正在尝试在ion-tab-bar 中显示ion-tabs 中的选项卡,具体取决于是否发出事件。我有一个*ngIf 用于条件渲染。代码如下:

<ion-tabs color="danger">
    <ion-tab-bar class="tab-bar" slot="bottom">
        <ion-tab-button *ngIf="!registerClicked" tab="tab1">
            <ion-icon name="thumbs-up"></ion-icon>
            <ion-label>{{'Transfer' | translate}}</ion-label>
        </ion-tab-button>

        <ion-tab-button tab="tab2">
            <ion-icon name="gift"></ion-icon>
            <ion-label>{{'Perks' | translate}}</ion-label>
        </ion-tab-button>
    </ion-tab-bar>
<ion-tabs>

这是事件发射器:

import { Events } from '@ionic/angular';
export class LoginModalPage 
  constructor(
      public event:Events
    ) { }

  public login() {
      this.event.publish('registerClicked', false);
  }
}

同样,还有一个函数将 registerClicked 设置为 true:

import { Events } from '@ionic/angular';
export class RegisterModalPage 
  constructor(
      public event:Events
    ) { }

  public register() {
      this.event.publish('registerClicked', true);
  }
}

在标签后面的代码中,

import { Events } from '@ionic/angular';
export class TabsPage {
  public registerClicked:boolean;
  constructor(
    public event: Events
  ) {
    this.event.subscribe('registerClicked', (data) =>{
      this.registerClicked = data;
    });
  }
}

现在代码在我运行 localhost:4200 时按预期工作,在单击按钮时调用登录函数时会显示 tab1,而当我单击执行 register() 函数的按钮时选项卡不可见.但是,当我构建一个 apk 并在设备上对其进行测试时,这不起作用。任何人都可以提供任何实现这一目标的见解吗?

【问题讨论】:

  • Events 在 Ionic 中不再支持。使用可观察的。
  • 我正在使用 ionic 4
  • 仍然选择我在答案中发布的解决方案。
  • 你也可以使用 BehaviourSubject.. 比简单的 Subjects 稍微好一点。
  • 可以找到另一个替代方案 here

标签: javascript angular ionic-framework ionic4


【解决方案1】:

为了将数据从一个页面更新到另一个页面,我们使用了事件库。但是 ionic 5 中不再提供事件。 打击是解决方案。 运行命令:

ionic generate service events        // this will create events provider

复制粘贴打击代码。

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

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

private fooSubject = new Subject<any>();

constructor() { }


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

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

从页面 A: 导入您的服务 在构造函数中初始化它 //

constructor(public events: EventsService){}

并发布事件,例如

 this.events.publishLogin(yourDataVariable);

在页面 B 中接收它: 导入您的服务 在构造函数中初始化它 //

    constructor(public events: EventsService){}

this.events.receiveLogin().subscribe((res:any)=>{
        console.log(res);
      })

【讨论】:

  • 我一会儿去看看
  • this.events.receiveLogin()... 应该在构造函数中吗?
  • 没关系。没问题
  • 让我知道结果。
  • 很高兴听到这个消息。
猜你喜欢
  • 1970-01-01
  • 2015-08-05
  • 1970-01-01
  • 1970-01-01
  • 2019-10-29
  • 1970-01-01
  • 1970-01-01
  • 2015-09-15
  • 1970-01-01
相关资源
最近更新 更多