Angular 4: unable to redirect from within subscription
After several unsuccessful attempts, I still cannot complete the redirect from within the subscription.
I want to catch a 401 error code to redirect the user to the login page, so in http.get.subscribe
if I have an error and if it is 401 I execute goLogin()
. This function should tell the router to go to the login page, but it is not. Everything works except routing.
Here's my code:
import { Http } from '@angular/http';
import { Injectable, NgZone } from '@angular/core';
import { CategoryFactory } from "./../factory/category.factory";
import { StatusFactory } from "./../factory/status.factory";
import { TicketFactory } from "./../factory/ticket.factory";
import { HeaderProvider } from "./../provider/header.provider";
import { Router, ActivatedRoute } from '@angular/router';
@Injectable()
export class TicketService {
public liste: TicketFactory[] = [];
constructor(private http: Http, private requestoptions:HeaderProvider, private _router:Router, private r:ActivatedRoute, private zone: NgZone) {
this.http.get('/issue', this.requestoptions.options)
.map(
res => res.json(),
err => err.json()
)
.subscribe(
(liste:any) => {
liste.forEach((l) => {
let t = new TicketFactory(
l.id,
l.title,
l.author,
l.text,
l.email,
new CategoryFactory(l.category.id, l.category.label),
new StatusFactory(l.status.id, l.status.label),
l.createdat,
l.priority,
l.sendto
);
this.liste.push(t);
})
},
(err:any) => {
if(err.json().code === 401) {
this.goLogin();
}
},
)
}
goLogin = (): void => {
this.zone.run(() => { console.log('go login'); this._router.navigate(['login']) })
}
getList = () : TicketFactory[] => {
return this.liste;
}
getTicket = (idticket):any => {
return this.http.get('/issue/' + idticket, this.requestoptions.options).map(res => res.json());
}
deleteTicket = (idticket):any => {
return this.http.delete('/issue/' + idticket, this.requestoptions.options)
.toPromise()
.then()
.catch();
}
}
Here app.routes.ts
import { Routes } from '@angular/router';
import { FormComponent } from './components/form/form.component';
import { LoginComponent } from './components/login/login.component';
import { SigninComponent } from './components/signin/signin.component';
import { TicketComponent } from './components/ticket/ticket.component';
import { TicketListComponent } from './components/ticketslist/ticketlist.component';
import { OnlyLoggedInUsersGuard } from './components/guard/guard.component';
export const appRoutes: Routes = [
{
path: 'signin',
component: SigninComponent,
canActivate: [OnlyLoggedInUsersGuard]
},
{
path: 'tickets/:id',
component: TicketComponent,
canActivate: [OnlyLoggedInUsersGuard]
},
{
path: 'tickets',
component: TicketListComponent,
canActivate: [OnlyLoggedInUsersGuard]
},
{
path: 'login',
component: LoginComponent
},
{
path: '',
component: FormComponent
},
{
path: '**',
redirectTo: ''
}
]
It goes to goLogin();
and gets executed console.log(...)
, but it doesn't redirect to the login page.
Here's the console output if it can help:
14:36:07.962 zone.js:2263 GET http://localhost:4200/user 401 (Unauthorized)
14:36:08.036 core.es5.js:1020 ERROR Response {_body: "{"code":401,"message":"Invalid authentication token"}", status: 401, ok: false, statusText: "Unauthorized", headers: Headers…}
14:36:08.048 zone.js:2263 GET http://localhost:4200/category 401 (Unauthorized)
14:36:08.110 core.es5.js:1020 ERROR Response {_body: "{"code":401,"message":"Invalid authentication token"}", status: 401, ok: false, statusText: "Unauthorized", headers: Headers…}
14:36:08.116 zone.js:2263 GET http://localhost:4200/issue 401 (Unauthorized)
14:36:08.122 ticket.service.ts:53 go login
14:36:08.479 zone.js:2263 GET http://localhost:4200/status 401 (Unauthorized)
14:36:08.575 core.es5.js:1020 ERROR Response {_body: "{"code":401,"message":"Invalid authentication token"}", status: 401, ok: false, statusText: "Unauthorized", headers: Headers…}
source to share
You must uninstall this.zone.run(...)
as it shouldn't be required. The app must remain in the angular scope. You also need it /
infront of the route.
Try swapping:
goLogin = (): void => {
this.zone.run(() => { console.log('go login'); this._router.navigate(['login']) })
}
to the next:
goLogin = (): void => {
console.log('go login');
this._router.navigate(['/login']) })
}
source to share