我有一个场景,我需要在两个组件之间传递数据,请找到下面的组件树场景。
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组件中,我无法从服务中获取数据。没有错误,实际上我无法调试。任何帮助都将不胜感激。
发布于 2016-11-01 13:25:37
这是因为服务是每个提供者的单例服务
由于您向G和B组件注入了不同的服务实例,因此无法将其存档。
您需要在一个公共模块中提供服务,如
@NgModule({
imports: [],
exports: [],
declarations: [Gcomponent, BComponent], // <-- components declared in same module
providers: [myCommService], // <--- service provided here
})https://stackoverflow.com/questions/40360860
复制相似问题