I have an api driven app using angular 2. I created a global service extending angular2-sails which, if the response to a call is 401 PLEASE_LOGIN, redirect the user to the signup component.
The problem is that when I redirect to signup component, the view (which load correctly tho) doesn't respond to user actions. There is no error, the components methods are calling and work when I, for example, click a button, but the view just doesn't react or update.
My setup is the following : My home component template has a reference to a user-sidebar.component. This sidebar component has an ngOnInit method who ask the backend for the authenticated user. When there is no authenticated user, the service who load it redirect to /signup
My user-sidebar.component ngOnInit method :
ngOnInit(): void
{
this._authService
.me()
.subscribe(
(resData: Object) => { this.user = resData.data; },
(err: any) => { console.log(err); }
);
}
The AuthService .me() method
me(): any
{
return this._appService.get('/me');
}
My app.service get method :
get(path: string, data: Object): Observable
{
return this._sailsService.get(path, data)
.catch(this.handleError.bind(this));
}
public handleError(err: Response): void
{
// If the server response with unhautorized, redirect to login / signup page
if(err.statusCode == 401 && err.error == 'PLEASE_LOGIN')
{
this._router.navigate(['/signup']);
}
return Observable.throw(err);
}
Not sure if an angular bug or my code, but my research gave nothing.
It seems change detection doesn't work
You can invoke change detection manually using
constructor(private zone:NgZone) {}
and run
this.zone.run(() => this._router.navigate(['/signup']));
Actually, I don't know why change detection isn't invoked automatically though.
It might be because router.navigate is called in an error handler but I don't see a good reason why this would cause it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With