【问题标题】:How to share a value between the components in angular 7如何在角度7中的组件之间共享一个值
【发布时间】:2019-11-28 17:04:52
【问题描述】:

我的 Angular 7 项目中有很多组件。厌倦了在组件之间共享一个值但无法正常工作。我在下面给出了我的代码。任何知道方法的人请帮助找到解决方案。

文件夹: 我的组件:

app ->

   ->power
   ->air
   ->pollution
   ->wind

power.component.ts:

@Output() public globalValue= new EventEmitter();

ngOnInit(){

 this.globalValue.emit('helloworld');

}

air.component.ts:

@Input() globalValue: string;

ngOnInit(){

console.log(this.globalValue); //Output should be helloworld

}

pollution.component.ts:

@Input() globalValue: string;

ngOnInit(){

console.log(this.globalValue); //Output should be helloworld

}

wind.component.ts:

@Input() globalValue: string;

ngOnInit(){

console.log(this.globalValue); //Output should be helloworld

}

【问题讨论】:

  • 不要使用输入或输出,它只在父子组件之间有效。只需在服务上设置变量并将服务注入组件的构造函数即可。

标签: angular6 angular7 angular8


【解决方案1】:

Angular 提供了许多我们可以在组件之间共享值的方法。

https://angular.io/guide/component-interaction

但正如我所见,您希望与多个组件共享。您可以创建一个服务,然后任何组件都可以订阅它并获得价值。

import { Injectable } from '@angular/core';
import { Subject }    from 'rxjs';

@Injectable()
export class GlobalService{

  // Observable string sources
  private globalValueSource = new Subject<string>();


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

  // Service message commands
  sendGlobalValue(value: string) {
    this.globalValueSource.next(value);
  }

}

在您的任何组件中,您都可以通过以下方式订阅它来获取值:

constructor(private globalService: GlobalService) {
    globalService.globalValueAnnounced$.subscribe(
      value => {
       console.log(value);
      });
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-11
    • 2020-04-27
    • 2019-04-12
    • 1970-01-01
    相关资源
    最近更新 更多