Issue
I have a functioning Angular 5 interceptor I use for authentication, but I'd like to add the capacity for the authentication service to be able to check local storage for an identity token before proceeding. Unfortunately, I've found that the app is loading so quickly that application is making calls using the interceptor, before the authentication service is able to update its status to announce that it's found a token in local storage.
It seems to me that I should be able to make a second interceptor that sits before the first one, and doesn't allow any events through until I see movement on the authentication service's ready$
observable. I'd understand how to arrange this if I was operating in a callback environment -- wait for the promise to resolve, once it resolves to trigger the callback and flow into the next link of the chain -- but I don't see how to make it work if I'm expected to return Observable<HttpEvent>
.
authService.ready$
is a BehaviorSubject
that starts false
, and is complete()
once the service's constructor finishes and we've found a token (or not). AuthenticationInterceptor
listens to authService.token$
to get the details to inject into the call. I'm sure this second interceptor is just going to be a couple lines, but I'm not familiar enough with rxjs to get this. Any ideas?
Edit: Seems like maybe I want to be using the (experimental?) APP_INITALIZER provider, except that even that's got problems. Angular4 APP_INITIALIZER won't delay initialization ... am I even on the right track?
Further Edits Yet: Final solution was...
import {
SomeAuthenticationService,
} from '@corporate/services';
export function authentication_preload(authService: SomeAuthenticationService) {
return () => authService.initialize();
}
@NgModule({
providers: [
{ provide: APP_INITIALIZER, useFactory: authentication_preload, deps: [SomeAuthenticationService], multi: true },
})
And then in the service, we just...
initialize(): Promise<any> {
return new Promise((resolve, reject) => {
// stuff that eventually resolve()s
});
}
The problem I had was that I couldn't seem to get to APP_INITIALIZER when I put this stuff in a Narwhal submodule, I had to kick it all the way to the top-level app that wrapped everything.
Solution
APP_INTIALIZER in the top-level NgModule, the one with access to bootstrap, was the answer.
Answered By - jesdynf
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.