gpt4 book ai didi

angular - 如何在 Angular http 拦截器中抛出可观察到的错误

转载 作者:太空狗 更新时间:2023-10-29 17:51:20 25 4
gpt4 key购买 nike

我试图在拦截器中抛出一个可观察到的错误,然后处理这个错误。但我不能。当success为false时,我也能收到订阅成功。

我试图在 next.handle(restReq) 中再次返回一个值。但是我失败了,没有订阅任何东西

restApi 是这样返回的

{
"success": false,
"data": {
"name": "Bad Request",
"message": "123",
"code": 0,
"status": 400,
"type": "yii\\web\\BadRequestHttpException"
}
}

auth.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/internal/Observable';

@Injectable({
providedIn: 'root'
})
export class AuthService {
private sessionUrl = '/wechat/session';

constructor(
private http: HttpClient
) { }

getSession(): Observable<any> {
return this.http.post<any>(this.sessionUrl, {});
}
}

auth.component.ts

import { Component, OnInit } from '@angular/core';
import { AuthService } from '@core/services/auth.service';
import { interval } from 'rxjs/internal/observable/interval';
import { switchMap, take } from 'rxjs/operators';

@Component({
selector: 'app-auth',
templateUrl: './auth.component.html',
styleUrls: ['./auth.component.scss']
})
export class AuthComponent implements OnInit {
constructor(
private authService: AuthService
) { }

ngOnInit(): void {
this.authService.getLoginQrcode()
.subscribe(
data => console.log(data),
error => console.log(error);
}
}

http-拦截器.ts

import { Injectable } from '@angular/core';
import {
HttpErrorResponse,
HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse
} from '@angular/common/http';

import { Observable } from 'rxjs';

@Injectable()
export class RestInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let baseUrl = environment.baseUrl + '/' + environment.version;
let headers = req.headers;
const restReq = req.clone({
headers,
withCredentials: true
});

return next.handle(restReq);
}
}

最佳答案

尝试在你的拦截器中这样做

return next.handle(request).map((event: HttpEvent<any>) => {
if (event instanceof HttpResponse && event.body && !event.body.success) {
throw new HttpErrorResponse({
error: 'your error',
headers: evt.headers,
status: 500,
statusText: 'Warning',
url: evt.url
});
}
return event;
);

关于angular - 如何在 Angular http 拦截器中抛出可观察到的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50181532/

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