在 Angular2 中捕获 401 异常
Catch 401 Exception in Angular2
当我尝试连接到未经授权的 URL 时,我进入 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
我的Home组件的代码是:
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;
});
}
}
并且此组件使用此服务:
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;
});
}
}
捕获此 401 异常的正确方法是什么?我应该在哪里执行此操作?
在组件中还是在服务中?最终目标是在发生任何 401 响应时重定向到登录页面。
您很可能希望从您的 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 runs = response.json();
return runs;
})
.catch(e => {
if (e.status === 401) {
return Observable.throw('Unauthorized');
}
// do any other checking for statuses here
});
然后组件中的 ngOnInit 将是:
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');
});
}
显然,您需要根据自己的需要调整代码并根据需要更改它,但是从 Http 捕获错误、抛出 Observable 错误并使用 err 回调来处理您的错误的过程组件应该可以解决您的问题。
当我尝试连接到未经授权的 URL 时,我进入 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
我的Home组件的代码是:
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;
});
}
}
并且此组件使用此服务:
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;
});
}
}
捕获此 401 异常的正确方法是什么?我应该在哪里执行此操作? 在组件中还是在服务中?最终目标是在发生任何 401 响应时重定向到登录页面。
您很可能希望从您的 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 runs = response.json();
return runs;
})
.catch(e => {
if (e.status === 401) {
return Observable.throw('Unauthorized');
}
// do any other checking for statuses here
});
然后组件中的 ngOnInit 将是:
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');
});
}
显然,您需要根据自己的需要调整代码并根据需要更改它,但是从 Http 捕获错误、抛出 Observable 错误并使用 err 回调来处理您的错误的过程组件应该可以解决您的问题。