Reputation: 723
I have Observable that contains big object inside. I want to pass only one property to child component as observable. I can you pipe in component, but I need to create one more observable for it. Can I make it inside html?
// this is service;
this.theObject$ = new BehaviourSubject<TheObject>(null);
this.theObject = {...alot,
title as string,
neededValue as number
};
this.theObject$.next(theObject);
get getTheObject (): Observable<TheObject> {
return this.theObject as Observable;
}
// component:
theObject: Observable<TheObject>;
ngOnInit(){
this.theObject = this.service.getTheObject;
}
// component html:
<div>
<span>{{(theObject | async).title}}</span>
<app-custom-component [neededValue$]="(theObject | async)?.neededValue"></app-custom-component>
</div>
//Custom Component
some: number;
@Input()'neededValue': Observable<number>;
ngOnInit(){
this.neededValue.subscribe(res => {
this.some = res;
})
}
I got an error here:
ERROR TypeError: Cannot read property 'subscribe' of undefined
I think problem is here: (theObject | async)?.neededValue. Is there a way to solve this without extra observables? Also I dont don't to pass to custom component all the big object.
Upvotes: 0
Views: 1553
Reputation: 98
If you only want to pass BehaviorSubject Value, why not use asObservable() method
theObject = new BehaviorSubject<TheObject>(null);
// This obs will contain the entire object
theObject$ = this.theObject.asObservable();
// This obs will contain only neededValue
theObjectNeededValue$ = this.theObject.asObservable().pipe(pluck('neededValue'));
Inside the component simply assign the service observable variables and use them with async
pipe or if you want to pass them to child component as observable.
// component.ts
theObject$ = this.service.theObject$;
theObjectNeededValue$ = this.service.theObjectNeededValue$;
// component html:
<div>
<span>{{(theObject$ | async).title}}</span>
<app-custom-component [neededValue$]="theObjectNeededValue$"></app-custom-component>
</div>
Upvotes: 2