在角度2中捕获401异常 [英] Catch 401 Exception in Angular2

查看:144
本文介绍了在角度2中捕获401异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试连接到未经授权的网址时,我进入Chrome:

  zone.js:1274 POST http: / localhost:8080 / rest / v1 / running 401(未经授权)
core.umd.js:3462 EXCEPTION:状态响应:401未经授权的URL:http:// localhost:8080 / rest / v1 / runs

我的家庭组件的代码是:



<$来自'@ angular / core'的p $ p> import {Component,OnInit};
import {Run} from../_models/run;
import {Http,Response} from@ angular / http;
import {RunService} from../_services/run.service;
import {Observable} fromrxjs;

@Component({
moduleId:module.id,
templateUrl:'home.component.html'
})

export class HomeComponent实现OnInit {
url:http:// localhost:8080 / rest / v1 / runs
username:string;
运行:运行[];

构造函数(private http:Http,private runService:RunService){

}

ngOnInit():void {
this。 username = JSON.parse(localStorage.getItem(currentUser))。username;
this.runService.getRuns()
.subscribe(runs => {
this.runs = runs;
});
}
}

此组件使用此服务:

  import {Injectable} from'@ angular / core';来自'@ angular / http'的
import {Http,Headers,Response,RequestOptions,URLSearchParams};
import {Observable} from'rxjs';
import'rxjs / add / operator / map'
import {AuthenticationService}来自./authentication.service;
import {Run} from../_models/run;

@Injectable()
导出类RunService {
url =http:// localhost:8080 / rest / v1 / runs;
private token:string;

构造函数(private http:Http,private authenticationService:AuthenticationService){

}

getRuns():Observable< Run []> {
return this.http.post(this.url,JSON.stringify({token:this.authenticationService.token}))
.map((response:Response)=> {
console.log(response.status);
if(response.status == 401){
console.log(NOT AUTHORIZED);
}

let run = response.json();
console.log(运行);
返回运行;
});
}
}

正确的方法来抓住这个401异常我该怎么办?
在组件或服务中?最终的目标是重定向到登录页面,如果有任何401响应发生。

解决方案

你最有可能会抛出错误从您的RunService可以抓住您的组件,可以进行路由到登录页面。以下代码可以帮助您:



在RunService中:



需要从rxjs导入catch运算符:

  import'rxjs / add / operator / catch'; 

您的getRuns()函数应该更改为

  getRuns():Observable< Run []> {
return this.http.post(this.url,JSON.stringify({token:this.authenticationService.token}))
.map((response:Response)=> {
let run = response.json();
return running;
})
.catch(e => {
if(e.status === 401){
return Observable.throw('Unauthorized');
}
//在其他任何状态检查
});

然后组件中的ngOnInit将为:

  ngOnInit():void {
this.username = JSON.parse(localStorage.getItem(currentUser))username
this.runService.getRuns()
.subscribe(runs => {
this.runs =运行;
},(err)=> {
if(err ==='Unauthorized'){this.router.navigateByUrl('/ login');
});
}

显然,您将需要根据自己的需求来满足代码并更改关于如果需要但是从Http捕获错误的过程,抛出一个Observable错误,并使用err回调来处理组件中的错误应该可以解决你的问题。


When i try to connect to an unauthorized URL i get in Chrome:

zone.js:1274 POST http://localhost:8080/rest/v1/runs 401 (Unauthorized)
core.umd.js:3462 EXCEPTION: Response with status: 401 Unauthorized for URL: http://localhost:8080/rest/v1/runs

The code of my Home Component is:

import {Component, OnInit} from '@angular/core';
import {Run} from "../_models/run";
import {Http, Response} from "@angular/http";
import {RunService} from "../_services/run.service";
import {Observable} from "rxjs";

@Component({
    moduleId: module.id,
    templateUrl: 'home.component.html'
})

export class HomeComponent implements OnInit{
    url: "http://localhost:8080/rest/v1/runs"
    username: string;
    runs: Run[];

    constructor(private http: Http, private runService: RunService) {

    }

    ngOnInit(): void {
        this.username = JSON.parse(localStorage.getItem("currentUser")).username;
        this.runService.getRuns()
            .subscribe(runs => {
                this.runs = runs;
            });
    }
}

And this component uses this service:

import { Injectable } from '@angular/core';
import {Http, Headers, Response, RequestOptions, URLSearchParams} from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map'
import {AuthenticationService} from "./authentication.service";
import {Run} from "../_models/run";

@Injectable()
export class RunService {
    url = "http://localhost:8080/rest/v1/runs";
    private token: string;

    constructor(private http: Http, private authenticationService: AuthenticationService) {

    }

    getRuns(): Observable<Run[]> {
        return this.http.post(this.url, JSON.stringify({ token: this.authenticationService.token }))
            .map((response: Response) => {
                console.log(response.status);
                if (response.status == 401) {
                    console.log("NOT AUTHORIZED");
                }

                let runs = response.json();
                console.log(runs);
                return runs;
            });
    }
}

What is the correct way to catch this 401 Exception and where should i do this? In the component or in the service? The final goal is to redirect to the Login page if any 401 response happens.

解决方案

You will most likely want to throw an error from your RunService that can be caught in your component which can do the routing to the log in page. The code below should help you out:

In RunService:

Need to import the catch operator from rxjs:

import 'rxjs/add/operator/catch';

And your getRuns() function should change to

getRuns(): Observable<Run[]> {
    return this.http.post(this.url, JSON.stringify({ token: this.authenticationService.token }))
        .map((response: Response) => {
            let runs = response.json();
            return runs;
        })
        .catch(e => {
            if (e.status === 401) {
                return Observable.throw('Unauthorized');
            }
            // do any other checking for statuses here
        });

and then the ngOnInit in the component will be:

ngOnInit(): void {
    this.username = JSON.parse(localStorage.getItem("currentUser")).username;
    this.runService.getRuns()
        .subscribe(runs => {
            this.runs = runs;
        }, (err) => {
            if (err === 'Unauthorized') { this.router.navigateByUrl('/login');
        });
}

Obviously you'll want to cater the code to your own needs and change it about if need be but the process of catching the error from Http, throwing an Observable error and using the err callback to handle the error in your component should solve your issue.

这篇关于在角度2中捕获401异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆