Ionic 2活动,发布和订阅不起作用

时间:2022-09-05 18:52:16

I'm trying to use Publish and Subscribe from ionic-angular

我正在尝试使用离子角度的发布和订阅

But I am not receiving any data nor error. Here are my codes

但我没有收到任何数据也没有收到错误。这是我的代码

Page 1

import {Events} from 'ionic-angular'

static get parameters(){
 return [[Events]];
}

constructor(Events)
{
 this.events = Events;

 this.events.publish("Msg", "Hello World");
}

Page 2

import {Events} from 'ionic-angular'

static get parameters(){
 return [[Events]];
}

constructor(Events)
{
 this.events = Events;

 this.events.subscribe("Msg", (data) => {
  console.log(data[0]);
 }
}

I'm using ionic-angular beta0.4.

我正在使用离子角度beta0.4。


I realize why it doesn't show on console.. Page 2 has to be loaded and ready before Page 1 initiate an event. If Page 1 were to initiate and publish before Page 2 is even loaded, Page 2 will not be able to grab that data.

我知道为什么它没有在控制台上显示..必须在第1页启动事件之前加载并准备好。如果第1页在加载之前启动并发布,则第2页将无法获取该数据。

SOLVED

3 个解决方案

#1


2  

I would need to use event as I'm constantly listening to my internet status on my first page, and I would like something to happen when my network is off on my second page

我需要使用事件,因为我一直在我的第一页上听我的互联网状态,我希望当我的网络在我的第二页上关闭时会发生一些事情

In the app I'm working right now, we're doing exactly the same. Please take a look at this plunker.

在我正在使用的应用程序中,我们正在做同样的事情。请看看这个plunker。

As you can see there, I've created a ConnectivityService whose main goal is to be informed when the connection status has changed (by your first page), and then notify to all the subscribers about that (your second page -and every page if you want-)

正如您在那里看到的,我创建了一个ConnectivityService,其主要目标是在连接状态发生变化时(通过您的第一页)通知,然后通知所有订阅者(您的第二页 - 以及每个页面,如果你要-)

ConnectivityService.ts

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

@Injectable()
export class ConnectivityService { 

  private connectionObserver: any;
  public connection: any;

  constructor(){
    this.connectionObserver = null;
    this.connection = Observable.create(observer => {
        this.connectionObserver = observer;
    });
  }

  // Send that information to all the subscribers
  public connectionHasChanged(private isOnline: bool) {
      this.connectionObserver.next(isOnline);
  }
}

With that being done, we just need to register the 'online' and 'offline' events in your first page (or do it like you're doing it in your app) and notify the service when the connection status changes:

完成后,我们只需在您的第一页中注册“在线”和“离线”事件(或者像在应用程序中执行此操作一样)并在连接状态更改时通知服务:

App.ts

import { Component } from "@angular/core";
import { ionicBootstrap, Platform } from 'ionic-angular/index';
import { HomePage } from './home.ts';
import { ConnectivityService } from 'connectivityService.ts';

@Component({
  template: '<ion-nav [root]="rootPage"></ion-nav>',
  providers: [ConnectivityService]
})
export class MyApp {
  constructor(private platform: Platform, private connectivityService: ConnectivityService) {
    this.addConnectivityListeners();
    this.rootPage = HomePage;
  }

  // Subscribe to online/offline events
  addConnectivityListeners(){

    // Handle online event
    document.addEventListener('online', () => {
      // Call the service, to indicate now there's connection (true)
      this.connectivityService.connectionHasChanged(true);
    }, false);

    // Handle offline event
    document.addEventListener('offline', () => {
      // Call the service, to indicate now there's no connection (false)
      this.connectivityService.connectionHasChanged(false);
    }, false);
  }
}

ionicBootstrap(MyApp);

And last but not least, then in your second page (or every page you need to) you can just subscribe to that service and handle the events

最后但并非最不重要的是,然后在您的第二页(或您需要的每个页面)中,您只需订阅该服务并处理事件

Home.ts

import { NavController } from 'ionic-angular/index';
import { Component } from "@angular/core";
import { ConnectivityService } from 'connectivityService.ts';

@Component({
  templateUrl:"home.html"
})
export class HomePage {

  public status: string = '';

  constructor(private nav: NavController, private connectivityService: ConnectivityService) {

    // We subscribe to the service, so if the connection status changes, we'll be notified.
    this.connectivityService.connection.subscribe((isOnline) => {
      this.handleConnectionStatus(isOnline);
    });
  }

  // Show a message when the connection changes
  public handleConnectionStatus(private isOnline: bool) {
    if(isOnline) {
      this.status = 'Online';
      console.log('Now is Online');
    } else {
      this.status = 'Offline';
      console.log('Now is offline');
    }
  }
}

#2


0  

Having read the posts here and other forums, seems like the part about subscribing to an event is rather tricky. I gather that understanding lifecycle hooks and how promises work is important to getting around the problem. The following works if you want a second page to be able to subscribe to a published event on an existing page:

阅读了这里和其他论坛的帖子,看起来订阅活动的部分相当棘手。我收集了理解生命周期钩子以及承诺如何工作对解决问题很重要。如果您希望第二页能够在现有页面上订阅已发布的事件,则以下情况有效:

this.navCtrl.setRoot(NextComponentPage, Parameters).then(()=>
{
    this.events.publish("user:created", userdetails);
});

#3


0  

Call the .subscribe inside constructor.

调用.subscribe内部构造函数。

and insted of console.log(data[0]) have you tried with console.log(data) ?

和console.log(data [0])的问题你试过console.log(数据)吗?

#1


2  

I would need to use event as I'm constantly listening to my internet status on my first page, and I would like something to happen when my network is off on my second page

我需要使用事件,因为我一直在我的第一页上听我的互联网状态,我希望当我的网络在我的第二页上关闭时会发生一些事情

In the app I'm working right now, we're doing exactly the same. Please take a look at this plunker.

在我正在使用的应用程序中,我们正在做同样的事情。请看看这个plunker。

As you can see there, I've created a ConnectivityService whose main goal is to be informed when the connection status has changed (by your first page), and then notify to all the subscribers about that (your second page -and every page if you want-)

正如您在那里看到的,我创建了一个ConnectivityService,其主要目标是在连接状态发生变化时(通过您的第一页)通知,然后通知所有订阅者(您的第二页 - 以及每个页面,如果你要-)

ConnectivityService.ts

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

@Injectable()
export class ConnectivityService { 

  private connectionObserver: any;
  public connection: any;

  constructor(){
    this.connectionObserver = null;
    this.connection = Observable.create(observer => {
        this.connectionObserver = observer;
    });
  }

  // Send that information to all the subscribers
  public connectionHasChanged(private isOnline: bool) {
      this.connectionObserver.next(isOnline);
  }
}

With that being done, we just need to register the 'online' and 'offline' events in your first page (or do it like you're doing it in your app) and notify the service when the connection status changes:

完成后,我们只需在您的第一页中注册“在线”和“离线”事件(或者像在应用程序中执行此操作一样)并在连接状态更改时通知服务:

App.ts

import { Component } from "@angular/core";
import { ionicBootstrap, Platform } from 'ionic-angular/index';
import { HomePage } from './home.ts';
import { ConnectivityService } from 'connectivityService.ts';

@Component({
  template: '<ion-nav [root]="rootPage"></ion-nav>',
  providers: [ConnectivityService]
})
export class MyApp {
  constructor(private platform: Platform, private connectivityService: ConnectivityService) {
    this.addConnectivityListeners();
    this.rootPage = HomePage;
  }

  // Subscribe to online/offline events
  addConnectivityListeners(){

    // Handle online event
    document.addEventListener('online', () => {
      // Call the service, to indicate now there's connection (true)
      this.connectivityService.connectionHasChanged(true);
    }, false);

    // Handle offline event
    document.addEventListener('offline', () => {
      // Call the service, to indicate now there's no connection (false)
      this.connectivityService.connectionHasChanged(false);
    }, false);
  }
}

ionicBootstrap(MyApp);

And last but not least, then in your second page (or every page you need to) you can just subscribe to that service and handle the events

最后但并非最不重要的是,然后在您的第二页(或您需要的每个页面)中,您只需订阅该服务并处理事件

Home.ts

import { NavController } from 'ionic-angular/index';
import { Component } from "@angular/core";
import { ConnectivityService } from 'connectivityService.ts';

@Component({
  templateUrl:"home.html"
})
export class HomePage {

  public status: string = '';

  constructor(private nav: NavController, private connectivityService: ConnectivityService) {

    // We subscribe to the service, so if the connection status changes, we'll be notified.
    this.connectivityService.connection.subscribe((isOnline) => {
      this.handleConnectionStatus(isOnline);
    });
  }

  // Show a message when the connection changes
  public handleConnectionStatus(private isOnline: bool) {
    if(isOnline) {
      this.status = 'Online';
      console.log('Now is Online');
    } else {
      this.status = 'Offline';
      console.log('Now is offline');
    }
  }
}

#2


0  

Having read the posts here and other forums, seems like the part about subscribing to an event is rather tricky. I gather that understanding lifecycle hooks and how promises work is important to getting around the problem. The following works if you want a second page to be able to subscribe to a published event on an existing page:

阅读了这里和其他论坛的帖子,看起来订阅活动的部分相当棘手。我收集了理解生命周期钩子以及承诺如何工作对解决问题很重要。如果您希望第二页能够在现有页面上订阅已发布的事件,则以下情况有效:

this.navCtrl.setRoot(NextComponentPage, Parameters).then(()=>
{
    this.events.publish("user:created", userdetails);
});

#3


0  

Call the .subscribe inside constructor.

调用.subscribe内部构造函数。

and insted of console.log(data[0]) have you tried with console.log(data) ?

和console.log(data [0])的问题你试过console.log(数据)吗?