Reputation: 19
I want to send a request for check user authentication.
My request :
'http://example.com/api/user/signin/check?token=' + token
I send a request inside ngOnInit()
at app.component.ts
and its work correctly .
the problem is
app.component.ts
send my request only once i need to send this request to server in each route change
Upvotes: 0
Views: 42
Reputation:
You can use Anglar Routing guards with the CanActivate guard interface.
@Injectable()
export class CheckAuthenticationGuard implements CanActivate {
constructor(/* Inject whatever you want here */) {}
public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean|UrlTree>|Promise<boolean|UrlTree>|boolean|UrlTree {
// Make request and return if you are authenticated or not.
}
}
@NgModule({
imports: [
RouterModule.forRoot([
{
path: 'home/',
component: HomeComponent,
canActivate: [CheckAuthenticationGuard]
},
{
path: 'otherRoute',
component: OtherComponent,
canActivate: [CheckAuthenticationGuard]
},
...
])
],
providers: [
...,
CheckAuthenticationGuard
]
})
class AppModule {}
Each time you will navigate to one of your defined routes, it will execute the CheckAuthenticationGuard
and if your canActivate
method returns true
, it will activate your route, otherwise, it will give you an error.
Upvotes: 1