Angular2兄弟组件通信,组件未订阅服务

时间:2016-04-25 22:25:19

标签: typescript angular

我尝试使用服务在同一页面中的兄弟组件之间进行通信,但是侦听组件没有触发订阅对象的更改:

服务

import {Injectable}     from 'angular2/core';
import {Observable}     from 'rxjs/Observable';
import {ReportTable} from '../classes/report.table.class';
import {Subject}    from 'rxjs/Subject';

@Injectable()
export class ReportService {

    private payload = new Subject<string>();

    // Observable string streams
    payload$ = this.payload.asObservable();

    constructor() { }

    public communicate(payload: string) {
        console.log('called2');
        this.payload.next(payload);
    }
}

广播组件

import {Component, Input} from 'angular2/core';
import {CORE_DIRECTIVES} from 'angular2/common';
import {FilterComponent} from '../reports/filter.component';
import {ReportService} from '../../services/report.service';

@Component({
    selector: 'filteroptions',
    templateUrl: '/Reports/filteroptions.template.html',
    providers: [ReportService]
})

export class FilterOptionsComponent {
    displayId: string;

    constructor(private reportService: ReportService) {             
    }


    passDisplayId(displayId: string) {
        console.log('called1');
        this.reportService.communicate(displayId);
    }
}

听力组件

import {Component, OnInit, OnDestroy} from 'angular2/core';
import {ReportService} from '../../services/riskreport.service';
import {ReportTable} from  '../../classes/riskreport.table.class';
import {HTTP_PROVIDERS}    from 'angular2/http';
import {DataTable} from 'primeng/primeng';
import {Column} from 'primeng/primeng';
import {Subscription}   from 'rxjs/Subscription';

@Component({
    selector: 'report-table',
    templateUrl: '/Reports/riskreport.table.template.html',
    providers: [ReportService, HTTP_PROVIDERS],
    directives: [DataTable, Column]
})

export class ReportTableComponent implements OnInit, OnDestroy {

    public subscription: Subscription;

    constructor(private reportService: ReportService) {
        this.subscription = this.reportService.payload$.subscribe(m => console.log('called3'));
    }

    ngOnInit() {}            

    // Prevent memory leak
    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
}

我可以在我的控制台中看到called1called2已被记录,但called3未被记录。为什么我的第二个组件没有收听/订阅?

1 个答案:

答案 0 :(得分:2)

您正在创建两个服务实例:

一个人在这里:

providers: [ReportService]

一个人在这里:

providers: [ReportService, HTTP_PROVIDERS],

每次将其添加到提供者数组时,您都要创建一个新实例。您希望将其包含在公共父元素的providers数组中。这将使他们都能访问相同的服务实例。

如果您使用HTTP_PROVIDERS有多个元素,则应将其移至公共父元素。