首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法在组件之间进行通信(角2)

无法在组件之间进行通信(角2)
EN

Stack Overflow用户
提问于 2016-11-01 13:16:28
回答 1查看 109关注 0票数 0

我有一个场景,我需要在两个组件之间传递数据,请找到下面的组件树场景。

代码语言:javascript
复制
     A
    / \
   B   C
  / \ / \
 D  E F  G

在这里,我需要将数据从G组件传递到位于同一屏幕上的B组件。

服务

代码语言:javascript
复制
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构成部分:

代码语言:javascript
复制
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构成部分:“

代码语言:javascript
复制
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组件中,我无法从服务中获取数据。没有错误,实际上我无法调试。任何帮助都将不胜感激。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-11-01 13:25:37

这是因为服务是每个提供者的单例服务

由于您向G和B组件注入了不同的服务实例,因此无法将其存档。

您需要在一个公共模块中提供服务,如

代码语言:javascript
复制
@NgModule({
    imports: [],
    exports: [],
    declarations: [Gcomponent, BComponent], // <-- components declared in same module
    providers: [myCommService], // <--- service provided here
})
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40360860

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档