我的 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
}
污染.component.ts:
@Input() globalValue: string;
ngOnInit(){
console.log(this.globalValue); //Output should be helloworld
}
风.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);
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句