我有一个场景需要在两个组件之间传递数据 请找到组件树的以下场景。
A
/ \
B C
/ \ / \
D E F G
这里我需要将数据从G组件传递到同一屏幕上的B组件
服务
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class myCommService {
private activeTabIndex = new Subject<number>();
public activeTabIndexs = new Subject<number>();
activeTab$ = this.activeTabIndex.asObservable();
selectedCount$=this.activeTabIndexs.asObservable();
constructor() { }
fnActiveTabIs(astronaut: number) {
debugger
this.activeTabIndex.next(astronaut);
}
fnSelected(astronauts: number) {
debugger
this.activeTabIndexs.next(astronauts);
}
}
G分量:
import { Component, OnInit, Input } from '@angular/core';
import { myCommService} from '../../../../shared/services/comm.service';
@Component({
selector: 'app-bl-view-widget-menu',
templateUrl: './bl-view-widget-menu.component.html',
styleUrls: ['./bl-view-widget-menu.component.css'],
inputs: ['id'],
providers: [myCommService]
})
export class BlViewWidgetMenuComponent implements OnInit {
isToggle: boolean = true;
i = 1;
constructor(private myCommService: myCommService) { }
id: Number;
ngOnInit() {
}
fn(data, id) {
debugger
this.i = this.i + 1;
// alert(this.i);
this.myCommService.fnSelected(1);
}
}
B组件:“
import { Component, OnInit } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { myCommService} from '../../shared/services/comm.service';
@Component({
// moduleId: module.id,
selector: 'app-bl-filter',
templateUrl: 'bl-filter.component.html',
styleUrls: ['bl-filter.component.css'],
providers: [myCommService]
})
export class BlFilterComponent implements OnInit {
showInfo: boolean = true;
activeTabIndex;
a;
constructor(
private myCommService: myCommService
) {
debugger
myCommService.selectedCount$.subscribe(
astronauts => {
this.a = astronauts;
});
}
ngOnInit() {
}
}
但是在这里我能够更新服务日期但是在B组件中我无法从服务中获取该数据。 没有错误,实际上我无法调试。 任何帮助将不胜感激。
答案 0 :(得分:3)
这是因为服务是每个提供商的单身人士
由于您要为G和B组件注入不同的服务实例,因此您无法实现此目标。
您需要在像
这样的通用模块中提供服务@NgModule({
imports: [],
exports: [],
declarations: [Gcomponent, BComponent], // <-- components declared in same module
providers: [myCommService], // <--- service provided here
})