如何在angular2中调用自定义事件服务

时间:2016-10-07 05:27:22

标签: angular typescript

我有自定义服务。我发送sting从一个组件到另一个组件,我有自定义EventService.I调用该函数,我使用debugger.execution控件不进入函数内部。这是我的代码。

event.service.ts

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

    @Injectable()
    export class EventService {

    _listeners: any = {};

    constructor() {}

    onEvent(type: any, listener: any) {
        // debugger;
        if (typeof this._listeners[type] === "undefined") {
            this._listeners[type] = [];
        }
        this._listeners[type].push(listener);
        // console.log('listeners = ', this._listeners, 'this = ',this);
    }

    fireEvent(event: any, obj: Object) {
        // debugger;
        // console.log('listeners = ', this._listeners, 'this = ',this);
        if (typeof event == "string") {
            event = {
                type: event
            };
        }
        if (!event.target) {
            event.target = this;
        }

        if (!event.type) { //falsy
            throw new Error("Event object missing 'type' property.");
        }

        if (this._listeners[event.type] instanceof Array) {
            var listeners = this._listeners[event.type];
            for (var i = 0, len = listeners.length; i < len; i++) {
                listeners[i].call(this, obj, event);
            }
        }
    }

    removeEvent(type: any, listener: any) {
        if (this._listeners[type] instanceof Array) {
            var listeners = this._listeners[type];
            for (var i = 0, len = listeners.length; i < len; i++) {
                if (listeners[i] === listener) {
                    listeners.splice(i, 1);
                    break;
                }
            }
        }
    }
}  

details.component.ts

import { Component, ViewEncapsulation, OnInit, AfterViewInit, Input, Output, EventEmitter } from '@angular/core';
import { ROUTER_DIRECTIVES, Router, ActivatedRoute } from '@angular/router';
import { DetailsService } from './details.service';
import { ItemService } from '../+gridview/gridview.service';
import { LimitFirstN } from './limitFirstN.pipe';
import { EventService } from '../../shared/service/event-service';


@Component({
 moduleId: module.id,
 selector: 'blank-page',
 pipes:[LimitFirstN],
 encapsulation: ViewEncapsulation.None,
 templateUrl: 'details.component.html',
 styleUrls:['details.component.css'],
 providers: [ DetailsService, ItemService,EventService],
 directives:[ ROUTER_DIRECTIVES ]
})
export class DetailsViewComponent implements OnInit, AfterViewInit  {


// @Output()
// drillDownTab = new EventEmitter<string>()
 errorMessageDetail:Object;
 //dummyInputs:any;
 inputData:any;
 summaryDetail:Object;
 sparkline:Object;
 tabItems: Array<any>;
 activeTabIndex : number;
 activeItem: any;
 window:any = window;

 spark:Array<any> = [];

 $ = this.window.$;
 deItems:Array<any> = [1,2,3];
 items:Array<any>;

 parcelSparks:Array<number>;
 nonParcelSparks:Array<number>;
 electronicSparks:Array<number>;
 manualSparks:Array<number>;
 auditSparks:Array<number>;
 auditPartial:Array<number>;
 auditNonParcel:Array<number>;
 auditNonParcelManual:Array<number>;
 codingValidSpark:Array<number>;
 codingExpSpark:Array<number>;
 previousCloseSpark:Array<number>;
 previousAmountSpark:Array<number>;

 ultranslate:number = 0;
 tanslateX:string;
 activeClient:string;
 activeClientCode:string
 itemss:string[] = [];
 tabClientCode:string;
 subData:string;
 limit:number = 3;
 error_type:string = 'all';
 isValidPrev:boolean = true;
 isValidNext:boolean = false;
 tabWidthCounter:number;
 isDisplay:string;
 tabCounter:number;
 hideSvgLoader:boolean = true;

 constructor(
     private itemDetailsService:DetailsService,
     private itemService:ItemService,
     private router: Router,
     private eventService: EventService,
     private route: ActivatedRoute) {
     this.activeTabIndex = 0;        
 }

 commanItemDetailsService(activeClient:string){
     this.itemDetailsService.loadItems(this.activeClient)
                 .subscribe((resp) => {
                     this.summaryDetail = resp.data;
                     this.hideSvgLoader = true;
                 });
 }

 commanErrorMessageService(activeClientCode:string,error_type:string) {
      this.itemDetailsService.errorMessage(this.activeClient,this.error_type)
            .subscribe((resp) => {
                     this.errorMessageDetail = resp;
                     this.inputData = resp.input;
                     this.hideSvgLoader = true;
                 });

 }

 ngOnInit() {
      this.hideSvgLoader = false;
     this.route.params
         .map(params => params['clientCode'])
         .subscribe((clientCode) => {
             this.activeClient = clientCode;

             this.commanItemDetailsService(this.activeClient);
         });

         this.commanErrorMessageService(this.activeClient,this.error_type)
    // this.itemDetailsService.errorMessage(this.activeClient,this.error_type)
     //Loading sparkline data
     this.sparkLine(this.activeClient)

     // Loading tab menus
     this.itemService.loadItems()
         .subscribe((resp) => {
             this.items = resp.data;
             this.hideSvgLoader = true;
         });

     //Loading header menu
     this.itemDetailsService.closeSummary()
         .subscribe(( data ) => {
             this.tabItems = data;
             this.tabWidthCounter = this.tabItems.length *160;
             this.tabCounter = this.tabItems.length;
             this.hideSvgLoader = true;
         });  
 }    

 onclickTab(index: number,activeClientCode:string) {
     this.activeItem = this.items[index];
     console.log("Activeclient",this.activeItem);
     console.log("secondActive",activeClientCode)
     this.activeTabIndex = index;
     this.sparkLine(activeClientCode);
     //this.sparkLine(this.activeItem.clientCode);

     this.activeClient = activeClientCode;
         this.commanItemDetailsService(activeClientCode);
         this.commanErrorMessageService(activeClientCode,this.error_type)
 }


goToError(id:number,clientCode:string){
   // console.log("This is active clientcode23",clientCode,this.activeClient)
     this.eventService.fireEvent('clientCodeChangeEvent', clientCode);
}
 navigateTo(errorId: number,clientCode:string) {
     // This is a temporary hack to make it work with router 2
     // "@angular/router": "2.0.0-rc.1". We will have to migrate the router to 
     // "@angular/router": "3.0.0-beta.1" which requires "@angular/router-deprecated": "2.0.0-rc.2"
     // As this will take long time to re-structure the code. We will be doing it in next sprint
     // We will migrate as given in the angular docs site
     // https://angular.io/docs/ts/latest/quickstart.html


     this.window.errorId = errorId;
    //  this.window.clientCode = clientCode;
      this.router.navigate(['/dashboard/errors',this.activeClient]);

 }

 convertSparkLneFormat( spakArr:Array<any> ) {
     let sparks:Array<number> = [];
     for(var i=0; i<spakArr.length; i++){
         sparks.push(spakArr[i].value);
     }
     return sparks;
 }

 ngAfterViewInit() {

 }

 createSpakline( elementId:string, sparklineData:Array<number>) {
     //let sparklineOptions = { type: 'line', height: 35, width: '100%', lineWidth: 2, valueSpots: { '0:': '#ccc' }, lineColor: '#2196f3', spotColor: '#ccc', fillColor: '', highlightLineColor: '#fff', spotRadius: 3 };
     let sparklineOptions = { type: 'line', height: 35, width: '100%', lineWidth: 2, valueSpots: { '0:': '#2196f3' }, lineColor: '#2196f3', spotColor: '#2196f3', fillColor: '', highlightLineColor: '#fff', spotRadius: 3 };
     let sparkline = document.querySelector(`#${elementId}`);
     this.$(sparkline).sparkline(sparklineData, sparklineOptions);
 }

 createBarChart(elementId: string, chartData: Array<number>) {

     let chartOptions = { type: 'bar', height: 35, barWidth: 6, barSpacing: 6, barColor: 'blue' };
     let barCharts = Array.from(document.querySelectorAll('.barChart'));
     barCharts.forEach((elem: any) => {
         this.$(elem).sparkline(chartData, chartOptions);
     });
 }

 prev() {
     if (this.ultranslate === 0) {
         // No more elements left in the left side
         return;
     }
     this.ultranslate += 160;
     this.tanslateX = `translateX(${this.ultranslate}px)`;

     const wpr: any = document.querySelector('.task-nav-wpr').getBoundingClientRect();
     const taskNav: any = document.querySelector('.task-nav').getBoundingClientRect();

     if (Math.abs(wpr.left - taskNav.left) <= 160 ) {
         this.isValidPrev = true;
         this.isValidNext = false;
     }

     if (Math.abs(wpr.left - taskNav.left) > 160) {
         this.isValidNext = false;
         //this.isValidPrev = false;
     }    
 }

scrollElement() {

     this.ultranslate -= 160;
     this.tanslateX = `translateX(${this.ultranslate}px)`;

     const wpr: any = document.querySelector('.task-nav-wpr').getBoundingClientRect();
     const taskNav: any = document.querySelector('.task-nav').getBoundingClientRect();

     if (Math.abs(wpr.right - taskNav.right) < 160 ) {
        this.isValidNext = true;
     }
     if (Math.abs(wpr.right - taskNav.right) > 160) {
        this.isValidPrev = false;
     }
}

 next() {

     this.ultranslate -= 160;
     this.tanslateX = `translateX(${this.ultranslate}px)`;
     const wpr: any = document.querySelector('.task-nav-wpr').getBoundingClientRect();
     const taskNav: any = document.querySelector('.task-nav').getBoundingClientRect();

     if (Math.abs(wpr.right - taskNav.right) < 160 ) {
        this.isValidNext = true;
        this.isValidPrev = false;
     }
     if (Math.abs(wpr.right - taskNav.right) > 160) {
        this.isValidPrev = false;
     }
 }

 sparkLine(clientCode: any) {
     this.itemDetailsService.sparklineData(clientCode)
         .subscribe((resp) => {
             this.sparkline = resp.data;
             this.parcelSparks = this.convertSparkLneFormat(resp.data.sparklineInput.sparklineNewBilling.parcel);
             this.nonParcelSparks = this.convertSparkLneFormat(resp.data.sparklineInput.sparklineNewBilling.nonParcel);
             this.electronicSparks = this.convertSparkLneFormat(resp.data.sparklineInput.sparklineNewBilling.electronic);
             this.manualSparks = this.convertSparkLneFormat(resp.data.sparklineInput.sparklineNewBilling.manual);
             this.auditSparks = this.convertSparkLneFormat(resp.data.inProgress.audit.parcel.complete);
             this.auditPartial = this.convertSparkLneFormat(resp.data.inProgress.audit.parcel.partial);
             this.auditNonParcel = this.convertSparkLneFormat(resp.data.inProgress.audit.nonParcel.complete);
             this.auditNonParcelManual = this.convertSparkLneFormat(resp.data.inProgress.audit.nonParcel.partial);
             this.codingValidSpark = this.convertSparkLneFormat(resp.data.inProgress.coding.valid);
             this.codingExpSpark = this.convertSparkLneFormat(resp.data.inProgress.coding.exception);
             this.previousCloseSpark = this.convertSparkLneFormat(resp.data.close.previousClose.invoices);
             this.previousAmountSpark = this.convertSparkLneFormat(resp.data.close.previousClose.amount);

             this.createSpakline('parcelSparkId', this.parcelSparks);
             this.createSpakline('nonParcelSparkId', this.nonParcelSparks);
             this.createSpakline('chartElectronic', this.electronicSparks);
             this.createSpakline('chartManual', this.manualSparks);
             this.createSpakline('auditComplete', this.auditSparks);
             this.createSpakline('auditPartial', this.auditPartial);
             this.createSpakline('nonParcelComplete', this.auditNonParcel);
             this.createSpakline('auditNonParcelManual', this.auditNonParcelManual);
             this.createSpakline('codingValid', this.codingValidSpark);
             this.createSpakline('codingException', this.codingExpSpark);
             this.createSpakline('previousClose', this.previousCloseSpark);
             this.createSpakline('previousCloseAmount', this.previousAmountSpark);
         });
    }

    drillDowns(data:any) {
        console.log("This is ",data);
         this.eventService.fireEvent('drillDownDetails', data);
    }
}

drilldown.component.ts

import { Component, OnInit, Input } from '@angular/core';
import { ROUTER_DIRECTIVES, Router, ActivatedRoute } from '@angular/router';
import { DetailsService } from '../+details/details.service';
import { DrillDownService } from './drilldown.service'
import { CORE_DIRECTIVES } from '@angular/common';
import { DROPDOWN_DIRECTIVES } from 'ng2-bootstrap/ng2-bootstrap';
import { EventService } from '../../shared/service/event-service';

@Component({
    moduleId: module.id,
    selector: 'drilldown-app',
    templateUrl: 'drilldown.component.html',
    styleUrls: ['drilldown.component.css'],
    providers: [ DetailsService, DrillDownService,EventService],
    directives: [ DROPDOWN_DIRECTIVES, ROUTER_DIRECTIVES ]
})

export class DrilldownComponent implements OnInit{

    activeClient:string;
    sparkLineDrilldown:Object;
    auditPartial1:Array<number>;
    auditSparks1:Array<number>;
    auditSparks12:Array<number>;

    clientCodeDrillDown:string;
    complete:string;
    drillDownTab1:string;
    drillDownTab2:string;
    subscription: any;
     @Input() major: Array<any>;
     @Input() major1: any;

     drillData:Array<any>;



    constructor(
        private drilldownSparkLine:DetailsService,
        private drilldownService:DrillDownService,
        private router: Router,
        private route: ActivatedRoute,
        private eventService: EventService
        ){

        }

        showChart() {
             this.drilldownSparkLine.sparklineData(this.clientCodeDrillDown)
             .subscribe((resp) => {
             this.sparkLineDrilldown = resp.data;

            // this.auditSparks12 = this.convertSparkLneFormat1(resp.data.inProgress.audit.parcel);

            //});

    (<any>$)('.drill-chart__cnt--left').highcharts({
        xAxis: {
            title: {enabled: false},
            categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
        },

         title: {
            text: ''
        },

        yAxis: {
            title: {
                text: ''
            },
            plotLines: [{
                value: 0,
                width: 1,
                color: '#808080'
            }]
        },
        exporting: {
            enabled: false
        },
        tooltip: {
            valueSuffix: '°C'
        },
        legend: {
            layout: 'vertical',
            align: 'right',
            verticalAlign: 'middle',
            borderWidth: 0
        },
         credits: {
            enabled: false
        },

        series: [{
            name: 'Complete',
            data: this.auditSparks12
        }]
    });

})
};

    ngOnInit() {
        debugger;
          this.eventService.onEvent('drillDownDetails', ( data:any ) => {
              debugger;
              console.log("Data",data)
        }); 

        this.drilldownService.loadTableData()
        .subscribe((resp:any) => {
            this.drillData = resp.drillDownTableData.drillDownNewBillingNonParcel;  
         this.route.params
         .map(params => params['activeClient'])
         .subscribe((activeClient) => {
             this.clientCodeDrillDown = activeClient;
             console.log(this.clientCodeDrillDown);
            // console.log(params[activeClient])
         });

          this.drilldownSparkLine.sparklineData(this.clientCodeDrillDown)
         .subscribe((resp) => {
             this.sparkLineDrilldown = resp.data;
             console.log(resp.data)
             //this.auditPartial1 = this.convertSparkLneFormat1(resp.data.inProgress.audit.parcel.partial);
             this.auditSparks1 = this.convertSparkLneFormat1(resp.data.inProgress.audit.parcel.complete);
             //console.log("mohit",this.auditPartial1)
         //});

     (<any>$)('.drill-chart__cnt--left').highcharts({
        xAxis: {
            title: {enabled: false},
            categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
        },

         title: {
            text: ''
        },

        yAxis: {
            title: {
                text: ''
            },
            plotLines: [{
                value: 0,
                width: 1,
                color: '#808080'
            }]
        },
        exporting: {
            enabled: false
        },
        tooltip: {
            valueSuffix: '°C'
        },
        legend: {
            layout: 'vertical',
            align: 'right',
            verticalAlign: 'middle',
            borderWidth: 0
        },
         credits: {
            enabled: false
        },

        series: [{
            name: 'Complete',
            data: this.auditSparks1
        }]
    });
     });
    }

    TabsData(data:any) {
        debugger;
        console.log("hellow my event",event)

    }

    convertSparkLneFormat1( spakArr:Array<any> ) {
     let sparks:Array<number> = [];
     for(var i=0; i<spakArr.length; i++){
         sparks.push(spakArr[i].value);
     }
     return sparks;
 }

}

1 个答案:

答案 0 :(得分:-2)

//检查此http://plnkr.co/edit/iCjyTqo0GbilPNN3ORcH?p=preview这可能有助于了解如何通过服务发出事件并在组件之间共享相同的数据。 主要变化是下面的屁股

import { Injectable, EventEmitter } from '@angular/core';

@Injectable()
export class commonService extends EventEmitter<any> {
  constructor() {
    super();
  }
}


import {Component, Input} from '@angular/core';
import {commonService} from './common.service';

@Component({
  selector: 'first-comp',
  template: `<div style="border: 1px solid #333333;" (click)="service.emit('Clicked on First component');">First Component , You can click here. Event: {{clickedSecond}}</div>`
})

export class firstComp {
  private clickedSecond: string = '';
  constructor(private service: commonService){
    service.subscribe((data) => {
      this.clickedSecond = data;
    })
  }
}



import {Component, Input} from '@angular/core';
import {commonService} from './common.service';

@Component({
  selector: 'second-comp',
  template: `<div style="border: 1px solid #333333;" (click)="service.emit('Clicked on Second component');">Second Component , You can click here. Event: {{clickedSecond}}</div>`
})

export class secondComp {
  private clickedSecond: string = '';
  constructor(private service: commonService){
    service.subscribe((data) => {
     this.clickedSecond = data;
    })
  }
}