我制作了一个具有不同页面的应用程序,以填充所需的每个主要对象。 该应用程序有一些大对象,很少使用它作为属性。
当前,我必须对组成ngOnInit()中的bigObject的每个littleObject进行订阅,并且必须每次导入所需的每个Subscription。
是否有可能(并且我应该这样做),使app.component拥有我需要的所有订阅,并在需要其他对象时调用它吗?
总结一下:
答案 0 :(得分:1)
对于解决方案,您可以提供两种服务。您也可以选中Stackblitz。
第一个是httpRequest服务
fakeReturn =
{
data: {
id: 1,
name: "fuchsia rose",
year: 2001,
color: "#C74375",
pantone_value: "17-2031"
},
data2: {
id: 2,
value: "fuchsia rose",
placeholder: "fake test",
text: "test",
}
}
getBigData(){
return of(this.fakeReturn);
}
第二个是数据服务。
private bigData$ = new BehaviorSubject<any>(null);
private child1Data$ = new BehaviorSubject<any>(null);
private child2Data$ = new BehaviorSubject<any>(null);
bigData: Observable<any> = this.bigData$.asObservable();
child1Data: Observable<any> = this.child1Data$.asObservable();
child2Data: Observable<any> = this.child2Data$.asObservable();
constructor(private requestService: HttpRequestService) {
this.requestService.getBigData()
.subscribe(bigData => {
this.setBigData(bigData);
});
}
setBigData(bigData: any) {
if (bigData) {
this.bigData$.next(bigData);
this.child1Data$.next(bigData.data);
this.child2Data$.next(bigData.data2);
}
else {
this.bigData$.next(null);
this.child1Data$.next(null);
this.child2Data$.next(null);
}
}
setChild1Data(childData: any) {
let bigValue = this.bigData$.value || { data: null, data2: null };
bigValue.data = childData;
this.bigData$.next(bigValue);
this.child1Data$.next(childData);
console.log("CHILD1 DATA -> ", childData);
}
setChild2Data(childData: any) {
let bigValue = this.bigData$.value || { data: null, data2: null };
bigValue.data2 = childData;
this.bigData$.next(bigValue);
this.child2Data$.next(childData);
console.log("CHILD2 DATA -> ", childData);
}
以及任何组件
this.dataService.child1Data.pipe(takeUntil(this.destroySubject$))
.subscribe(child1 => {
this.child1Data = child1;
console.log("component child 1 ->", this.child1Data);
});
this.dataService.child2Data.pipe(takeUntil(this.destroySubject$))
.subscribe(child2 => {
this.child2Data = child2;
console.log("component child 2 ->", this.child2Data);
});
this.dataService.bigData.pipe(takeUntil(this.destroySubject$))
.subscribe(bigData => {
this.bigData = bigData;
console.log("component bigData ->", this.bigData);
});