Angular - RxJS/Observable: כיצד להגדיר סדר עבור שיטות pipe
יש לי מתודה run במחלקה Some שמחזירה Observable ויש לה pipe בתוך המתודה הזו. ויש לי עוד pipe כאשר מבצעים את המתודה run.
import { of } from 'rxjs';
import { map, tap, delay } from 'rxjs/operators';
class Some {
run() {
return of('Some request').pipe(
tap((res) => {
console.log('First -> ', res);
})
);
}
}
new Some().run().pipe(
map(res => console.log(`Second -> ${res}`))
).subscribe();
והקונסולה תדפיס
First -> Some requestSecond -> Some requestהשאלה שלי היא: אני צריך לבצע כמה פעולות בתוך המתודה לאחר שזה pipe -> new Some().run().pipe() יושלם. אם מבוסס על הדוגמה הזו אני רוצה לראות בקונסול
ראשון :
Second -> Some requestואחר
First -> Some requestתשובה #1
אתה יכול להעביר את פונקציית המיפוי לשיטה run:
run(mappingFunction: (Observable<any>) => Observable<any>) {
return of('Some request').pipe(
map(res => mappingFunction(res)),
tap(console.log)
);
}
כמובן שאתה יכול ליישם את המושג הזה על כל פונקציה שתרצה להעביר לכל אופרטור של RxJS.
תשובה #2
אתה יכול להעביר פונקציית אופרטור כארגומנט לפקודת run:
run(operator) {
return of('Some request').pipe(
operator,
tap((res) => {
console.log('First -> ', res);
})
);
}
run(input$ => input$.pipe(tap(v => console.log(v, “second”))).subscribe()
