gpt4 book ai didi

exception - 在 Angular2 中捕获 401 异常

转载 作者:太空狗 更新时间:2023-10-29 17:11:22 27 4
gpt4 key购买 nike

当我尝试连接到未经授权的 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

我的主页组件的代码是:

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 回调处理组件中的错误的过程应该解决您的问题。

关于exception - 在 Angular2 中捕获 401 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39870972/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com