4

经过多次不成功的尝试,我仍然无法从订阅内部重定向。

我想捕获错误代码 401 以将用户重定向到登录页面,所以http.get.subscribe如果我有错误并且如果它是 401 我执行goLogin()。这个函数必须告诉路由器导航到登录页面,但它没有。一切正常,除了路由。

这是我的代码:

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();
    }
}

这里是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: ''
    }
]

它进入goLogin();console.log(...)执行,但不会重定向到登录页面。

如果有帮助,这是控制台输出:

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…}
4

2 回答 2

0

您应该删除它,this.zone.run(...)因为它不应该是必需的。应用程序应保持在角度范围内。您还需要/路线的前方。

尝试交换:

goLogin = (): void  => {
    this.zone.run(() => { console.log('go login'); this._router.navigate(['login']) })
}

到以下:

goLogin = (): void  => {
    console.log('go login');
    this._router.navigate(['/login']) })
}
于 2017-09-26T15:14:04.800 回答
0
//try this
 this._router.navigateByUrl(['login']
于 2017-06-21T12:22:34.960 回答