how to create a httpGate with Obserservable
how to create a httpGate with Obserservable
I have multiple requests which I want to pause until the authenticate http request has been confirm. This means I should have a http gate which request can go thru without having to auth and some will wait until authenticate token comes back.
I thought of using switchmap like below code but then it will not work because a observable switch with a return value.
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req)
.switchMap((event: HttpEvent<any>, index: number): Observable<HttpEv
ent<any>> => req.url.indexOf('/index')>-1)
return Observable.of(event);
)
.do(
next: function(data)
console.log(data);
,
error: function(error: HttpErrorResponse)
// retry
// or handling data
);
Error MESSAGE
You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
1 Answer
1
Instead of do it from intercept()
, I would recommend you create your own ApiService
, expose a few methods and make all of your HTTP calls from there.
intercept()
ApiService
Inside your ApiService
, you could have for example:
ApiService
Get(url: string): Observable
return of(0).pipe(
switchMap(() => this.waitForAuth()),
switchMap(() => this.$http.get(url))
);
So every time you call your endpoint, your request will hang there until the user is authenticated. Or it'll make the call immediately if the user is already authenticated.
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Thank you for answering my question, Xinan. I need to keep the intercept pattern unless this is my last resort because of time and restructuring majority of the codes which I don’t have the liberty to change. Could I use inner observable to control outer observable and any stream that comes into this will pause?
– roger
Sep 3 at 21:44