Reputation: 6926
I have the following ngrx effect. Inside "map" I have a condition. How can I stop the effect immediately without continue to the mergeMap.
@Effect()
myEffect$: Observable < Action > = this.actions$.pipe(
ofType('INIT_ACADEMY_DOMAIN'),
map((action: any) => {
const url = 'http://www.academy.xyzq';
if (1 === 1) {
// Make this effect stop immediately and do nothing more
}
action.url = url;
return action;
}),
mergeMap((action: any) =>
this.http.get(action.url).pipe(
switchMap((data: any) => {
return [{
type: 'INIT_ACADEMY',
payload: {
academy: data.academy
}
}];
})
)),
catchError(() => of ({
type: 'INIT_IT_FAILED'
}))
);
Upvotes: 4
Views: 3280
Reputation: 778
You should consider using the filter
function to filter out actions based on your condition:
@Effect()
myEffect$: Observable < Action > = this.actions$.pipe(
ofType('INIT_ACADEMY_DOMAIN'),
filter((x) => 1 === 1),
mergeMap((action: any) =>
this.http.get(action.url).pipe(
switchMap((data: any) => {
return [{
type: 'INIT_ACADEMY',
payload: {
academy: data.academy
}
}];
})
)),
catchError(() => of ({
type: 'INIT_IT_FAILED'
}))
);
Alternatively you could just dispatch a new action if your condition is true and create a simpler effect that executes the part inside your mergeMap
function.
You should try to keep your effects as simple as possible. If your effect does a lot of logic / condition checks, it is hard to find a suitable name that captures what the effect really does.
Upvotes: 2
Reputation: 9764
You can try like this.
@Effect()
myEffect$: Observable < Action > = this.actions$.pipe(
ofType('INIT_ACADEMY_DOMAIN'),
map((action: any) => {
const url = 'http://www.academy.xyzq';
if (1 === 1) {
// Make this effect stop immediately and do nothing more
return null;
}
action.url = url;
return action;
}),
mergeMap((action: any) =>
if(action){
return this.http.get(action.url).pipe(
switchMap((data: any) => {
return [{
type: 'INIT_ACADEMY',
payload: {
academy: data.academy
}
}];
})
} else{
return null;
}
)),
catchError(() => of ({
type: 'INIT_IT_FAILED'
}))
);
Upvotes: 1