本文介绍了http拦截器中的Angluar2路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Angular 2.4.8.与后端的通信是通过 REST 进行的.在每个请求中,我需要在标头中发送 X-Auth-Token.令牌存储在会话中.当令牌过期时,服务器返回 401 状态.在这种情况下,我希望应用程序转到登录页面.

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.

我在我的项目中添加了 http 拦截器

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)?

编辑 2018-01-22

我的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 { }

InitResolverService 中,我有一些逻辑要在第一次导航时执行,然后发出 true 并完成流.

where in InitResolverService I have some logic to do on first navigation and then emit true and complete stream.

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(['/']);
            }
        });
    }
}

推荐答案

我们通过编写自己的自定义 http 服务来解决这个问题,我们通过 REST 使用所有 http 请求.

we are solve this case with write own custom http-service that we using all http request via REST.

你也可以自定义http-service;

Also you can with custom http-service;

  • 中心 api 路径
  • 使用令牌创建标头
  • 处理所有 HTTP 错误结果甚至 401

简单代码示例

import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { ErrorObservable } from 'rxjs/observable/ErrorObservable';

export const API_PATH = "http://apipath"

@Injectable()
export class CustomHttpService {

    constructor(
        private http: Http,
        public router: Router) { }

    headerWithToken(): Headers {
        const headers = new Headers();
        headers.set('Authorization', 'bearer ' + localStorage.getItem('TOKEN'));
        headers.set('Content-Type', 'application/json');
        return headers;
    }

    get(params: URLSearchParams, method: string): Observable<any> {
        const url = `${API_PATH}/${method}`;
        return this.http.get(url, {params: params, headers: this.headerWithToken()})
        .map(
            res => <Array<any>>res.json()
        )
        .catch(err => {
            const result = this.handleErrors(err, this);
            return result;
        });
    }

    // put same way

    // post same way

    // delete same way

    public handleErrors(error: Response, obj: any): ErrorObservable {
        const errData = error.json();
        if (error.status === 401) {
            obj.router.navigate(['/login']);
        } else if (errData.message) {
            // give a message or something
        } else {
            console.log(errData);
        }
        return Observable.throw(error.json());
    }

}

这篇关于http拦截器中的Angluar2路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 08:48