如何在 angular 7 中的组件之间共享一个值
How to share a value between the components in angular 7
我的 angular 7 project.Tired 中有很多组件可以在组件之间共享一个值但没有 working.I 已经给出了我的代码 below.Anyone 知道方法请帮忙找到解决方案。
文件夹:
我的组件:
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
}
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);
});
}
我的 angular 7 project.Tired 中有很多组件可以在组件之间共享一个值但没有 working.I 已经给出了我的代码 below.Anyone 知道方法请帮忙找到解决方案。
文件夹: 我的组件:
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
}
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);
});
}