Angular 4:无法从订阅内部重定向

时间:2017-06-21 11:13:40

标签: javascript angular angular-router

经过多次尝试失败后,我仍然无法从订阅中重定向。

我想抓住错误代码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…}

2 个答案:

答案 0 :(得分:0)

//try this
 this._router.navigateByUrl(['login']

答案 1 :(得分: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']) })
}