在Angular5中,我想将值从一个组件传递到另一个组件(同级)。为此,我创建了如下通用服务:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DataService {
private data = {};
constructor() { }
setOption(option, value) {
this.data[option] = value;
}
getOption() {
return this.data;
}
}
在组件#1中,我写了以下内容:
onSubmit(form: NgForm){
this._dataService.setOption('image', form.value.image);
}
在组件#2中,我想获取该值并想像这样对其进行控制台:
ngOnInit() {
this.sharedData = this._dataService.getOption();
console.log(this.sharedData.image);
}
但是,它在控制台中显示undefined
。
答案 0 :(得分:2)
您可以改用observable:
export class DataService {
private data = new BehaviorSubject<any>({});
// behavior subject will keep in mind the last value so if the parent
// emit before the first component is mounted, it will not receive the value
// subject would not that is the difference
// private data = new Subject<any>(); <-- Arnaud Denoyelle's solution
constructor() { }
setOption(option, value) {
const options = this.data.getValue();
options[option] = value;
this.data.next(options);
// .next will emit a new value to every subscription
}
get option() {
return this.data.asObservable();
}
}
像这样使用它:
ngOnInit() {
this.sub = this._dataService.option.subscribe(data => {
this.sharedData = data; // each time option will change, sharedData will too
console.log(this.sharedData);
});
}
ngOnDestroy() {
this.sub.unsubscribe(); // clear to avoid memory leak
}
组件1不会更改:
onSubmit(form: NgForm){
this._dataService.setOption('image', form.value.image);
}
答案 1 :(得分:1)
尝试将data
更改为BehaviorSubject
或Subject
(如果不需要初始数据),例如:
private data = new BehaviorSubject<any>({});
然后更改您的setOption
和getOption
方法以使用它:
setOption(value){
this.data.next(value);
}
getOption(): Observable<any>{
return this.data.asObservable();
}
然后组件#2中的用户订阅getOption
返回的Observable:
this._dataService.getOption()
.subscribe((data)=>{
this.sharedData = data;
});
仅记得通过rxjs的takeUntil
或其他方法取消订阅该Observable,以避免内存泄漏。