I want to create a new operator like map
. but the different is whatever map returns I need to clone it using JSON.parse(JSON.stringify(value))
.
Because I return an object from my store (Subject
), and I don't want somebody to change it, or it's inner properties.
I copy the map
singture to my mapToVM
function, but I can't find any way to use pipe
or manipulate the return results.
Is it possible to change the return results by wrapping the map
operator?
So I try to return the map
function and take the source as Observable
, but typescript
import { map, Observable, OperatorFunction, Subject } from "rxjs";
console.clear();
const store = new Subject<{ company: { id: number } }>();
store.pipe(map((s) => s.company)).subscribe((company) => {
console.log({ company });
});
function mapToVM<T, R>(
project: (value: T, index: number) => R
): OperatorFunction<T, R> {
// JSON.parse(JSON.stringify(source));
return map(project);
}
store.pipe(mapToVM((s) => s.company)).subscribe((company) => {
console.log({ company });
});
store.next({ company: { id: 1 } });
CodePudding user response:
you can use the static pipe function:
function jsonClone<T>(): OperatorFunction<T, T> {
return pipe(map((source) => JSON.parse(JSON.stringify(source))));
}