I use Angular 2.4.8. Communication with backend is via REST. In each request I need to send X-Auth-Token
in header. The token is stored on session. When token is outdated server returns 401 status. In such a case I want application to go to login page.
I added http interceptor to my project
@Injectable()
export class HttpInterceptor extends Http {
constructor(backend: XHRBackend
, defaultOptions: RequestOptions
, private router: Router
) {
super(backend, defaultOptions);
}
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
return super.request(url, options).catch((error: Response) => {
if ((error.status === 401 || error.status === 403) &&
(window.location.href.match(/\?/g) || []).length < 2) {
// tslint:disable-next-line:no-console
console.log('The authentication session expires.');
window.sessionStorage.removeItem('auth-token');
window.location.href = window.location.href + '/login';
// this.router.navigate(['/login']);
return Observable.empty();
}
return Observable.throw(error);
});
}
}
and it works well except. But I don't use router but plain redirect and whole application reloads. When I changed commenting to
// window.location.href = window.location.href + '/login';
this.router.navigate(['/login']);
the app doesn't follow the link. How to make router to work (navigate)?
edit 2018-01-22
My app-routing.module.ts
const routes: Routes = [
{
path: 'login',
component: LoginComponent,
resolve: {
boolean: InitResolverService
}
},
{
path: '**',
redirectTo: 'system'
}
];
@NgModule({
imports: [
RouterModule.forRoot(
routes
// , { enableTracing: true } // <-- debugging purposes only
)
],
exports: [
RouterModule
]
})
export class AppRoutingModule { }
where in InitResolverService
I have some logic to do on first navigation and then emit true
and complete stream.
And LoginComponent
@Component({
selector: 'app-login',
templateUrl: 'login.component.html',
styleUrls: ['login.component.less']
})
export class LoginComponent implements OnInit {
private username: FormControl;
private password: FormControl;
public form: FormGroup;
public displayDialog = false;
isLoginButtonEnabled = true;
isResetButtonVisible = false;
constructor(
private authService: AuthenticationService,
private router: Router,
private route: ActivatedRoute,
private initService: InitResolverService
) {
this.username = new FormControl(Validators.required);
this.password = new FormControl(Validators.required);
this.form = new FormGroup({
Username: this.username,
Password: this.password
});
this.form.setValue({
Username: '',
Password: ''
});
this.displayDialog = true;
}
ngOnInit() {
this.initService.showSplash();
this.authService.canActivate(this.route.snapshot, this.router.routerState.snapshot).subscribe(x => {
if (x) {
this.router.navigate(['/']);
}
});
}
}
at your app.module.ts you should add:
at your HttpInterceptor:
I didn't use interceptor for that. with every API call I use
.catch
to catch errors and pass to this function:hope this helps.
This code works for me:
we are solve this case with write own custom http-service that we using all http request via REST.
Also you can with custom http-service;
Simple code sample