当我尝试连接到未经授权的网址时,我会进入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
我的主页组件的代码是:
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响应,最终目标是重定向到“登录”页面。
答案 0 :(得分:31)
您很可能希望从您的组件中捕获可以在组件中捕获的错误,该错误可以路由到登录页面。以下代码可以帮助您:
在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错误并使用错误回调处理组件中的错误的过程应该解决你的问题。