Angular2和Ionic中事件的问题

时间:2017-11-21 18:54:31

标签: angular events ionic2 ionic3

我在我的应用程序中设置了一个计时器组件,它基本上是一个倒数计时器。完成倒计时后,我希望将两个不同的事件发送到两个不同的页面(ListItemDetails)。
ItemDetails页面是我显示所选订单项的页面,如果我在某个订单的ItemsDetail页面并且计时器用完它应该执行一些逻辑。
问题是这只适用于List页面中的最后一项(包含订单),我需要它来处理List页面中的所有订单

- 的修改 -
我不假装同时打开2个页面。问题是该事件应该为List页面中的每个订单“启动”,而不是为最后一个订单执行此操作。

timer.ts

timerTick() {
  setTimeout(() => {
    if (!this.timer.runTimer) { return; }
    this.timer.timeRemaining--;
    this.timer.displayTime = this.getSecondsAsDigitalClock(this.timer.timeRemaining);
    if (this.timer.timeRemaining > 0) {
      this.timerTick();
    }
    else {
      this.timer.hasFinished = true;
      this.events.publish('timer:finished',this.timer.hasFinished,this.order);
      this.events.publish('timer:popnav'+this.order,this.timer.hasFinished,this.order)
    }
  }, 1000);
}

list.ts

constructor(private navCtrl: NavController,
            private navParams: NavParams,
            private events : Events) {
  this.events.subscribe("timer:finished", (value,id) => {
    ...
  })
}

itemTapped(event, sector,user) {
  this.navCtrl.push(ItemDetailsPage, { sector: sector, user: user });
}

list.html

<div *ngFor="let sector of order.sectors">
   <button ion-item detail-none class='col last-item' [disabled]="sector.timeOut" (click)="itemTapped($event,sector,order.user)">
     <ion-row>
       <ion-col col-3>
         <div class='timer-line'>
           <timer [timeInSeconds]="timeInSeconds(sector)" [order]="sector.orderId"></timer>
         </div>
       </ion-col>
       <ion-col class='pull-right'>
         {{ sector.name }} <i class="material-icons">arrow_forward</i>
       </ion-col>
     </ion-row>
   </button>
</div>

项-details.ts

constructor(private navCtrl: NavController,
            public navParams: NavParams, 
            public events: Events) {
  this.selectedOrder = navParams.get('sector');
  this.events.subscribe("timer:popnav"+this.selectedOrder.orderId,(value,id) => {
    ...
  });
}

ionViewWillLeave(){
  this.events.unsubscribe("timer:popnav"+this.selectedOrder.orderId);
}

1 个答案:

答案 0 :(得分:1)

好的我觉得我理解你的问题: - )

我试图重写一个例子来解决同样的问题。

如果问题是您希望在详细信息页面上收到完成的每个计时器的事件,则必须订阅"timer:popnav"而不是"timer:popnav"+this.selectedOrder.orderId,并且同时订阅计时器中的发布:{ {1}}代替this.events.publish('timer:popnav',this.timer.hasFinished,this.order)

这些活动在我的应用上运行良好,你可以在这里查看我推送的源代码:https://github.com/proustibat/timer-angular-ionic-issue

希望它可以提供帮助。

我总结了这里的主要文件:

<强> List.ts:

this.events.publish('timer:popnav'+this.order,this.timer.hasFinished,this.order)

<强> List.html

import {Component} from '@angular/core';
import {Events, NavController, NavParams} from 'ionic-angular';
import {ItemDetailsPage} from "../item-details/item-details";

@Component({
    selector: 'page-list',
    templateUrl: 'list.html',
})
export class ListPage {

    order = {
        user: "username",
        sectors: [{
            name: "First Sector",
            timeOut: false,
            orderId: 1
        },{
            name: "Second Sector",
            timeOut: false,
            orderId: 2
        },{
            name: "Third Sector",
            timeOut: false,
            orderId: 3
        }]
    };

    constructor(public navCtrl: NavController, public navParams: NavParams, private events : Events) {
        this.events.subscribe("timer:finished", ( value, id ) => {
            console.log("ListPage Event [timer:finished]: ", value, id);
        });
    }

    itemTapped(event, sector,user) {
        this.navCtrl.push(ItemDetailsPage, { sector: sector, user: user });
    }
}

<强>项-details.ts

<ion-header>
    <ion-navbar>
        <ion-title>List</ion-title>
    </ion-navbar>
</ion-header>

<ion-content padding>
    <ion-card *ngFor="let sector of order.sectors">
        <ion-card-header>
            <ion-card-title>{{ sector.name }}</ion-card-title>
        </ion-card-header>

        <ion-card-content>
            <button ion-button detail-none [disabled]="sector.timeOut" (click)="itemTapped($event, sector, order.user)">
                Open details
            </button>
            <timer [timeInSeconds]="5" [order]="sector.orderId"></timer>
        </ion-card-content>
    </ion-card>
</ion-content>

<强>项-details.html

import { Component } from '@angular/core';
import {Events, NavController, NavParams} from 'ionic-angular';

@Component({
    selector: 'page-item-details',
    templateUrl: 'item-details.html',
})
export class ItemDetailsPage {

    selectedOrder:any;
    eventsReceived:Array<any> = [];

    constructor(private navCtrl: NavController, public navParams: NavParams, public events: Events) {
        this.selectedOrder = navParams.get('sector');
        // this.events.subscribe("timer:popnav"+this.selectedOrder.orderId,(value,id) => {
        this.events.subscribe("timer:popnav",(value,id) => {
            console.log("ItemDetailsPage Event [timer:popnav]: ", value, id);
            this.eventsReceived.push({
                value,
                id
            });
        });
    }

    ionViewWillLeave(){
        // this.events.unsubscribe("timer:popnav"+this.selectedOrder.orderId);
        this.events.unsubscribe("timer:popnav");
    }

}

然后是你的计时器组件:

<强> timer.ts

    <ion-navbar>
        <ion-title>Item Details</ion-title>
    </ion-navbar>

</ion-header>



<ion-content padding>


    <ion-card>
        <ion-card-header>
            <ion-card-title>Selected Order</ion-card-title>
        </ion-card-header>
        <ion-card-content>
            <ion-item>
                name: {{selectedOrder.name}}
            </ion-item>
            <ion-item>
                timeOut: {{selectedOrder.timeOut}}
            </ion-item>
            <ion-item>
                orderId: {{selectedOrder.orderId}}
            </ion-item>
        </ion-card-content>
    </ion-card>

    <ion-card *ngFor="let event of eventsReceived">
        <ion-card-header>
            <ion-card-title>Event received</ion-card-title>
        </ion-card-header>
        <ion-card-content>
            <ion-item>
                Event id: {{event.id}}
            </ion-item>
            <ion-item>
                Event value: {{event.value}}
            </ion-item>
        </ion-card-content>
    </ion-card>
</ion-content>

<强> timer.html

import {Component, EventEmitter, Input} from '@angular/core';
import {Events} from "ionic-angular";

export interface ITimer {
    seconds: number;
    secondsRemaining: number;
    runTimer: boolean;
    hasStarted: boolean;
    hasFinished: boolean;
    displayTime: string;
}

@Component({
    selector: 'timer',
    templateUrl: 'timer.html'
})
export class TimerComponent {

    @Input() timeInSeconds: number;
    @Input() order: any;
    public timer: ITimer;

    constructor(private events:Events) {
        console.log('Hello TimerComponent Component');
    }

    ngOnInit() {
        this.initTimer();
    }

    hasFinished() {
        return this.timer.hasFinished;
    }

    initTimer() {
        console.log("Timer.initTimer: order = ", this.order);
        if(!this.timeInSeconds) { this.timeInSeconds = 0; }

        this.timer = <ITimer>{
            seconds: this.timeInSeconds,
            runTimer: false,
            hasStarted: false,
            hasFinished: false,
            secondsRemaining: this.timeInSeconds
        };

        this.timer.displayTime = this.getSecondsAsDigitalClock(this.timer.secondsRemaining);
    }

    startTimer() {
        this.timer.hasStarted = true;
        this.timer.runTimer = true;
        this.timerTick();
    }

    pauseTimer() {
        this.timer.runTimer = false;
    }

    resumeTimer() {
        this.startTimer();
    }

    timerTick() {
        setTimeout(() => {
            if (!this.timer.runTimer) { return; }
            this.timer.secondsRemaining--;
            this.timer.displayTime = this.getSecondsAsDigitalClock(this.timer.secondsRemaining);
            if (this.timer.secondsRemaining > 0) {
                this.timerTick();
            }
            else {
                this.timer.hasFinished = true;
                this.events.publish('timer:finished',this.timer.hasFinished,this.order);
                // this.events.publish('timer:popnav'+this.order,this.timer.hasFinished,this.order);
                this.events.publish('timer:popnav',this.timer.hasFinished,this.order);
            }
        }, 1000);
    }



    getSecondsAsDigitalClock(inputSeconds: number) {
        var sec_num = parseInt(inputSeconds.toString(), 10); // don't forget the second param
        var hours   = Math.floor(sec_num / 3600);
        var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
        var seconds = sec_num - (hours * 3600) - (minutes * 60);
        var hoursString = '';
        var minutesString = '';
        var secondsString = '';
        hoursString = (hours < 10) ? "0" + hours : hours.toString();
        minutesString = (minutes < 10) ? "0" + minutes : minutes.toString();
        secondsString = (seconds < 10) ? "0" + seconds : seconds.toString();
        return hoursString + ':' + minutesString + ':' + secondsString;
    }

}