I want to return an observable (line 6) as DataObject. Line 9 is listening to store changes, so when there is a store change - lines 10,11,12 execute but not before store change right? Or Will it get the existing value in the store and execute the block (lines 10,11,12). But if store hasnt changed yet, will line 14 wait until line 10,11,12 execute or will it return line 14 as empty object? What can I do if I want to listen to changes -> map the data from store into DataObject and return it as observable, not before that?
class DataObject {
propA: string = '';
propB: string = '';
propC: SecondDataObject;
}
getDataModel(): Observable<DataObject> {
let data = new DataObject();
this.store.pipe(select(appState)).subscribe((val) => {
const data = new DataObject();
data.propA = val.propA;
data.propB = val.propB;
data.propC = val.propC;
});
return of(data);
}
CodePudding user response:
You can achieve that without subscribing to the selector
, just by using the map operator and retuning the Observable
itself, like the following:
getDataModel(): Observable<DataObject> {
return this.store.pipe(select(appState)).pipe(
map((val) => {
const data = new DataObject();
data.propA = val.propA;
data.propB = val.propB;
data.propC = val.propC;
return data;
})
);
}
CodePudding user response:
You can return a new observable like below :-
getDataModel():Observable<DataObject>()
{
let data = new DataObject();
return new Observable((observer) => {
this.store.pipe(select(appState)).subscribe((val)=>{
data.propA = val.propA;
data.propB = val.propB;
data.propC = val.propC;
observer.next(data);
observer.complete();
}));
});
}