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.





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



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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)