Angular6 如何在angular 7中的组件之间共享值
在我的angular 7项目中,我有很多组件。我很想在组件之间共享一个值,但不工作。我在下面给出了我的代码。任何知道方法的人请帮助找到解决方案 文件夹: 我的组件:Angular6 如何在angular 7中的组件之间共享值,angular6,angular7,angular8,Angular6,Angular7,Angular8,在我的angular 7项目中,我有很多组件。我很想在组件之间共享一个值,但不工作。我在下面给出了我的代码。任何知道方法的人请帮助找到解决方案 文件夹: 我的组件: app -> ->power ->air ->pollution ->wind power.component.ts: @Output() public globalValue= new EventEmitter(); ngOnInit(){ this.globalVa
app ->
->power
->air
->pollution
->wind
power.component.ts:
@Output() public globalValue= new EventEmitter();
ngOnInit(){
this.globalValue.emit('helloworld');
}
@Input() globalValue: string;
ngOnInit(){
console.log(this.globalValue); //Output should be helloworld
}
@Input() globalValue: string;
ngOnInit(){
console.log(this.globalValue); //Output should be helloworld
}
@Input() globalValue: string;
ngOnInit(){
console.log(this.globalValue); //Output should be helloworld
}
air.component.ts:
@Output() public globalValue= new EventEmitter();
ngOnInit(){
this.globalValue.emit('helloworld');
}
@Input() globalValue: string;
ngOnInit(){
console.log(this.globalValue); //Output should be helloworld
}
@Input() globalValue: string;
ngOnInit(){
console.log(this.globalValue); //Output should be helloworld
}
@Input() globalValue: string;
ngOnInit(){
console.log(this.globalValue); //Output should be helloworld
}
污染.component.ts:
@Output() public globalValue= new EventEmitter();
ngOnInit(){
this.globalValue.emit('helloworld');
}
@Input() globalValue: string;
ngOnInit(){
console.log(this.globalValue); //Output should be helloworld
}
@Input() globalValue: string;
ngOnInit(){
console.log(this.globalValue); //Output should be helloworld
}
@Input() globalValue: string;
ngOnInit(){
console.log(this.globalValue); //Output should be helloworld
}
wind.component.ts:
@Output() public globalValue= new EventEmitter();
ngOnInit(){
this.globalValue.emit('helloworld');
}
@Input() globalValue: string;
ngOnInit(){
console.log(this.globalValue); //Output should be helloworld
}
@Input() globalValue: string;
ngOnInit(){
console.log(this.globalValue); //Output should be helloworld
}
@Input() globalValue: string;
ngOnInit(){
console.log(this.globalValue); //Output should be helloworld
}
Angular提供了许多方法,我们可以通过这些方法在组件之间共享值 但正如我所见,您希望与多个组件共享。您可以创建一个服务,然后任何组件都可以订阅该服务并获得价值
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);
}
}
不要使用输入或输出,它仅在父组件和子组件之间有效。只需在服务上设置变量,并将服务注入组件的构造函数中。