首页 > 解决方案 > 使用共享服务将值传递给兄弟组件

问题描述

我想将选择列表中的值 - ListComponentComponent 传递给兄弟组件 - DisplayComponentComponent 并在 DisplayComponentComponent 的模板中显示该值。我想为此使用共享服务。我创建了服务,并传递了改变的价值。但是,当我想在我的显示组件中 console.log 这个值时,我什么也看不到。这是我的代码。

显示组件

export class DisplayComponentComponent implements OnInit {
  val: any;
  constructor(private myService: MyServiceService) { }

  ngOnInit() {
    this.myService.val.subscribe(result => {
        this.val = result
      });
  }
}

列表

export class ListComponentComponent implements OnInit {
  list: any;
  selected: string;
  constructor(private myService: MyServiceService) { }

  ngOnInit() {
    this.list = [
      {
        text: 'test1',
        value: 'test1'
      },
      {
        text: 'test2',
        value: 'test2'
      },
      {
        text: 'test3',
        value: 'test3'
      }
    ]
    this.selected = this.list[0].value;
    this.myService.update(this.selected);
  }
  getSelected(val) {
    this.selected = val;
    this.myService.update(this.selected);
  }
}

服务

@Injectable()
export class MyServiceService {
  public source = new Subject<any>();
  val = this.source.asObservable();

  update(input: any) {
     this.source.next(input);
  }
  constructor() { }

}

该值应显示在此处:

<p>
  {{result}}
</p>

https://stackblitz.com/edit/angular-7lhn9j?file=src%2Fapp%2Fmy-service.service.ts

标签: javascriptangular

解决方案


如果您想显示应用程序负载的值,您需要将主题更改为BehaviorSubject

    private _onChanged: BehaviorSubject<any> = new BehaviorSubject({});
    public val= this._onChanged.asObservable(); 

  update(input: any) { 
     this._onChanged.next(input);
  }
  constructor() { }

演示


推荐阅读