Reputation: 39444
I am subscribing an Observable as follows:
this.service.post(request).subscribe(
(value: Response> => {
// Do something with value
},
(error) => {
this.state = State.Invalid;
// Show errors on page
},
() => {
this.state = State.Completed;
// Redirect to new page:
this.router.navigate(['done'], { state: { v: value } });
}
);
Basically I am posting a request to an API and then I need to:
How to access value in completed? This is why I need to access it:
this.router.navigate(['done'], { state: { v: value } });
Should I move this line to the next
function?
(value: Response> => {
// Do something with value
// Redirect here
}
Upvotes: 1
Views: 544
Reputation: 6706
You can't do that within the complete
callback directly, because it takes zero args.
If you want to access the value after both SUCCESSFUL and ERRORED, you can use RxJS
operators, like the following:
this.service
.post(request)
.pipe(
tap((value: Response) => {
// do something with the Response value here
}),
catchError((err) => {
// catch the error here, and return observable of anything that refer to an error not to the Response value.
return of('ANYTHING_REFER_TO_ERROR');
})
)
.subscribe((value: Response | string) => {
// Here you can access the value,
// which will be the Response value if there is no error,
// or the value your returned from catchError.
});
Upvotes: 2