I have a scenario where I have to get the request payload passed when the service fails so I can return back along with error response. My code goes like below.
#Effect() doGetEvents$: Observable<Action> = this.actions$
.ofType(EVENTS)
.switchMap((action) => {
let eventDate = action.payload.date;
return this.http.service(action.payload);
})
.map(res => {
// success
if (res.status) {
return CustomActions.prototype.eventsResponse({ type: EVENTS_RESPONSE, payload: res.payload });
}
//failure
return CustomActions.prototype.EventsErrorResponse({
type: CustomActions.EVENTS_ERROR_RESPONSE,
payload: {
status: res.status,
errorMessage: res.errorMessage,
billDate: '10/01/2016', // <--- I need the eventDate got from the above switchMap
errorType: CustomActions.EVENTS + '_ERROR'
}
});
});
I tried passing like
.switchMap((action) => {
let eventDate = action.payload.date;
return [eventDate, this.http.service(action.payload)];
})
but this won't execute the http call and won't return the response on .map() args.
Also the are options to make the eventDate outside the scope of Effects and assign it when service fails but it is not a cleaner approach, there should be some way passing data round not sure what I missed!
If you want to include information from the payload, along with the HTTP service's result, you can use the map operator, like this:
.switchMap((action) => {
return this.http
.service(action.payload)
.map(result => [action.payload.date, result]);
})
.map(([date, result]) => { ... })
Related
I need to call an API that can return errors, warnings or success.
If it returns warnings the user must able to accept the warning and I should send the same payload + acceptWarning: true.
I need to display an ionic modal and wait for the user's response to see if he accepts or cancel the warning.
What should be the best way to achieve that?
Right now I have something like this:
#Effect()
public Assign$ = this.actions$.pipe(
ofType(myActions.Assign),
map(action => action.payload),
exhaustMap(assignment =>
this.assignService.assign(assignment).pipe(
switchMap(() => {
this.errorService.showPositiveToast(' Assigned Successfully');
return [
new LoadAssignments(),
new LoadOtherData()
];
}),
catchError(error =>
from(this.openErrorModal(error)).pipe(
switchMap(({ data = '' }) => {
if (data === 'Accept') {
return of(new Assign({ ...assignment, acceptWarning: true }));
}
return of(new AssignShipmentFailure());
})
)
)
)
)
);
async openErrorModal(response: any) {
const errorModal = await this.modalCtrl.create({
component: ErrorValidationPopup,
componentProps: {
response: response,
},
});
await errorModal.present();
return errorModal.onDidDismiss();
}
But it is not triggering the Assign action again. Thanks for your help
If any error occurred in the effect's observable (or any Observable), then its stream emitted no value and it immediately errored out. After the error, no completion occurred, and the Effect will stop working.
To keep the Effect working if any error occurred, you have to swichMap instead of exhaustMap, and handle the errors within the inner observable of the switchMap, so the main Observable won't be affected by that.
Why use switchMap?
The main difference between switchMap and other flattening operators is the cancelling effect. On each emission the previous inner observable (the result of the function you supplied) is cancelled and the new observable is subscribed. You can remember this by the phrase switch to a new observable
You can try something like the following:
#Effect()
public Assign$ = this.actions$.pipe(
ofType(myActions.Assign),
map(action => action.payload),
switchMap(assignment =>
this.assignService.assign(assignment).pipe(
switchMap(() => {
this.errorService.showPositiveToast('Assigned Successfully');
return [
new LoadAssignments(),
new LoadOtherData()
];
}),
catchError(error =>
from(this.openErrorModal(error)).pipe(
map(({ data = '' }) => {
if (data === 'Accept') {
return new Assign({ ...assignment, acceptWarning: true });
}
return new AssignShipmentFailure();
})
)
)
)
)
);
here is my complete code function example:
public scan(formData: Object): Observable<any> {
let url = this.remoteUrl;
let result;
this.onlineService.isOnline$.subscribe( (isOnline) => {
if (isOnline) {
console.log('services is online connected');
result = this
._http
.post(url, formData, { headers: headers })
.pipe(map((res: any) => {
// console.log(res);
let response = res;
return response;
}),
catchError(error => {
if (error.status === 401 || error.status === 403) {
// handle error
}
return throwError(error);
}));
}else{
console.log('services are offline');
result = this.dbService.getByIndex('safety', 'code', formData['trafoStation']).subscribe( (location) => {
return location;
});
}
});
console.log(result);
return result;
};
actually, I need to run two different services based on an internet connection if the connection is available then call server API otherwise store on offline ngx-indexed-db.
i have stored data both online and offline.
getting undefined in result.
Result is undefined because it's an async operation: this.onlineService.isOnline$ has not emmited yet, but you already have return result, thus the undefined.
Also, the way you combine your observables is not right. You should NOT create new observables (and subscribe to them) in a subscribe method. That lead to weird side effects and memory leaks down the line.
Here's my proposal to get your code to work. I used the switchMap operator to return either your apiCall or your store operation based on isOnline$ value. SwitchMap is used to combine a higher observable with an inner observable and flatten the stream. It will also interupt the current subscription each time isOnline$ emits:
private _handleServices(formData, isOnline: boolean): Observable<any> {
console.log(`services are ${isOnline ? 'online': 'offline'}`);
const url = this.remoteUrl;
const apiCall$ = this._http.post(url, formData, { headers: headers })
.pipe(
catchError(error => {
if (error.status === 401 || error.status === 403) {
// handle error
}
return throwError(error);
})
);
const store$ = this.dbService.getByIndex('safety', 'code', formData['trafoStation']);
return (isOnline) ? apiCall$ : store$;
}
public scan(formData: Object): Observable<any> {
return this.onlineService.isOnline$.pipe(
switchMap((isOnline) => this._handleServices(formData, isOnline)),
tap(res => console.log(res))
);
};
Then, when you call your function in your component, you will call it like this:
this.scan(formData).subscribe(res => /* handle scan response */);
I posted a similar question several days ago but I have made some changes and commenting on that question was becoming tedious, so it was recommended I ask a new question.
The idea is that I want to execute four equations synchronously. Inside those equations are HTTP requests. I have two of the equations working properly and but there is one equation that involves two POST requests and a GET requests. The second requests relies on the first and the third request relies on the second.
I have tried several different methods to get this to work. I have tried flattening my promises, returning the promises. All kinds of things, with no luck. I am not sure where I am going wrong.
Synchronous code snippet:
this.getData1(user, userID).then(() =>
{
this.getData2(user, userID)
.then(() =>
{
this.getData3(user, lan).then(() =>
{
this.userCheck(user);
})
});
});
I have getData2 and getData3 working.
getData1 looks like:
getData1(user: string, id: string){
console.log('grabbing CC information', id, user);
return new Promise((resolve, reject) =>
{
var status: string;
this._apiService.getAssertion(id).subscribe((data: any) =>
{
let assert = data.toString();
this._apiService.getToken(assert).subscribe((data: any) =>
{
let tkn = data.access_token.toString();
this._apiService.ccMeta(tkn, guid).subscribe((data: any) =>
{
parseString(data, (err, result) =>
{
if (err)
{
throw new Error(err);
}
else
{
status = result['entry']['content'][0]['m:properties'][0]['d:status'][0];
this.ccData.push(
{
key: 'userStatus',
value: status
})
}
});
});
});
});
resolve()
});
}
I also tried something like this previously. It did not work either.
apiService.getAssertion(id).then(assert =>
{
return apiService.getToken(assert.toString(), user);
}).then(data =>
{
return apiService.ccMeta(data.access_token.toString(), id);
}).then(parseStringPromise).then(information =>
{
this.ccData.push(
{
key: 'userStatus',
value: information.entry
});
});
Inside this function the getAssertion function is a POST request. The getToken function is another POST request that relies on the assertion from the first POST request. Finally, ccMeta is a get request that relies on the token from the second POST request.
I would expect getData1 to execute first, then getData2, then getData3, and finally, userCheck. Inside getData1 I need the assertion, then the token, and then get request to execute synchronously. The code snippet above is not executing correctly. The assertion is not properly being used in the getToken equation.
I would greatly appreciate some help.
Since these HTTP calls are in fact observables and not promises, I think you should look into observable composition using pipe and switchMap for instance. If you still want you method to return a promise, it could look like this:
getData1(user: string, id: string) {
console.log('grabbing CC information', id, user);
return new Promise((resolve, reject) => {
this._apiService.getAssertion(id)
.pipe(
switchMap((data: any) => {
let assert = data.toString();
return this._apiService.getToken(assert);
}),
switchMap((data: any) => {
let tkn = data.access_token.toString();
return this._apiService.ccMeta(tkn, guid);
}),
)
.subscribe(
data => {
parseString(data, (err, result) => {
if (err) {
reject(new Error(err));
return;
}
const status: string = result['entry']['content'][0]['m:properties'][0]['d:status'][0];
this.ccData.push({
key: 'userStatus',
value: status
});
resolve();
});
},
);
});
}
I have the function below:
getUser(userId: string) : Observable<any> {
var getUserURL = `/api/users/${userId}`,
getUserStatus = this.getUserStatus();
return this.http.get<any>(getUserURL).pipe(
catchError(this.handleError('getUser - Get User failed', null))
);
}
This returns the data from response from REST API for this URL /api/users/${userId} to toPromise
Is there any way that I can return the object that include the response data from REST API + local data(getUserStatus) which is Boolean in this case.
Thanks
Your request is not returning a Promise unless it isn't included in your example. You have an Observable.
Assuming I understand your question correctly. If you want to return the HTTP response + the local status you would do something like this using piped operators:
Service
getUser(userId: string) : Observable<any> {
const path = `/api/users/${userId}`
const userStatus = this.getUserStatus();
return this.http.get<any>(path)
.pipe(
map((response: any) => {
return { response, userStatus };
}),
catchError(this.handleError('[USER]::getUser Failed', null))
);
}
Component
this.getUser(1000).subscribe(({response, userStatus}) => {
// Handle response and status
console.log('RESPONSE', response);
console.log('USER_STATUS', userStatus);
});
Like #mtputlz said you're returning an Observable. If you want to return your reponse which is in your case a boolean. Then we can convert the obserable to a promise:
async getUser(userId: string) : any {
var getUserURL = `/api/users/${userId}`,
getUserStatus = this.getUserStatus();
return await this.http.get<any>(getUserURL).pipe(
catchError(this.handleError('getUser - Get User failed', null))
).toPromise();
}
My use case is to map an Observable to redux actions of success and failure. I make a network call (with a function that gives promise), if it succeeds I have to forward a success action, if it fails than an error action. The Observable itself shall keep going. For all I could search, RxJS do not have a mechanism for this catching the error and retrying the original. I have following solution in my code which I am not happy with:
error$ = new Rx.Subject();
searchResultAction$ = search$
.flatMap(getSearchResultsPromise)
.map((resuls) => {
return {
type: 'SUCCESS_ACTION',
payload: {
results
}
}
})
.retryWhen((err$) => {
return err$
.pluck('query')
.do(error$.onNext.bind(error$));
});
searchErrorAction$
.map((query) => {
return {
type: 'ERROR_ACTION',
payload: {
query,
message: 'Error while retrieving data'
}
}
});
action$ = Observable
.merge(
searchResultAction$,
searchErrorAction$
)
.doOnError(err => console.error('Ignored error: ', err))
.retry();
action$.subscribe(dispatch);
i.e I create a subject, and push errors into that subject and create an Observable of error actions from that.
Is there a better alternative of doing this in RxJS that I am missing? Basically I want to emit a notification of what error has occurred, and then continue with whatever the Observable is already doing.
This would retry failed queries:
var action$ = search$
.flatMap(value => {
// create an observable that will execute
// the query each time it is subscribed
const query = Rx.Observable.defer(() => getSearchResultsPromise(value));
// add a retry operation to this query
return query.retryWhen(errors$ => errors$.do(err => {
console.log("ignoring error: ", err);
}));
})
.map(payload => ({ type: "SUCCESS_ACTION", payload }));
action$.subscribe(dispatcher);
If you don't want to retry, but just want to notify or ignore errors:
var action$ = search$
.flatMap(value => {
// create an observable that will execute
// the query each time it is subscribed
const query = Rx.Observable.defer(() => getSearchResultsPromise(value));
// add a catch clause to "ignore" the error
return query.catch(err => {
console.log("ignoring error: ", err);
return Observable.empty(); // no result for this query
}));
})
.map(payload => ({ type: "SUCCESS_ACTION", payload }));
action$.subscribe(dispatcher);