Angular 角度blob响应,不转换回json
我正在使用一个拦截器,以便在我的API不可用时创建数据模拟;我还没准备好。mocking服务将所有响应作为blob处理回前端,但是我不知道如何将响应作为流转换回json结果。我发现在resquest中,我可以声明响应类型为blob,但它仍然不能返回流的结果 让我用代码来说明它 我的模拟服务Angular 角度blob响应,不转换回json,angular,Angular,我正在使用一个拦截器,以便在我的API不可用时创建数据模拟;我还没准备好。mocking服务将所有响应作为blob处理回前端,但是我不知道如何将响应作为流转换回json结果。我发现在resquest中,我可以声明响应类型为blob,但它仍然不能返回流的结果 让我用代码来说明它 我的模拟服务 import { Injectable } from '@angular/core'; import { HttpResponse, HttpEvent, HttpHandler, HttpI
import { Injectable } from '@angular/core';
import {
HttpResponse,
HttpEvent,
HttpHandler,
HttpInterceptor,
HttpRequest,
} from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { delay } from 'rxjs/operators';
import { MockResponseOptions } from './mock.types';
import { handleEchoRequest } from './responses/echo';
import { handleCasesRequest } from "./responses/cases";
@Injectable()
export class MockInterceptor implements HttpInterceptor {
// Mock API handler configuration
private handlers = {
GET: {
// 'assets': handleGetAssetRequest
// ...add new GET request handlers here
'/cases': handleCasesRequest
},
POST: {
'/echo': handleEchoRequest,
// ...add new POST request handlers here
},
};
constructor() { }
/**
* Intercepts HTTP requests and returns mock response if configured and actual response otherwise
* @param {HttpRequest} request The request to be mocked.
* @param {HttpHandler} next The real HTTP request handler
* @returns {Observable<HttpEvent>}
*/
intercept(
request: HttpRequest<unknown>,
next: HttpHandler
): Observable<HttpEvent<unknown>> {
const mockHandler = this.getMockHandler(request);
if (mockHandler) {
console.log('[REQUEST INTERCEPTED]', request);
const mockResponseConfig = mockHandler(request);
return this.getResponse(mockResponseConfig, request);
}
// If no mock handler is available, perform the original request
return next.handle(request);
}
/**
* Creates an Observable HttpResponse based on a mock response configuration.
* @param {MockResponseOptions} options The mock response configuration
* @param {HttpRequest<unknown>} request The original HTTP request
*/
getResponse(
options: MockResponseOptions,
request: HttpRequest<unknown>
): Observable<HttpEvent<Blob>> {
console.log('[REQUEST after interception]', request, options);
return of(
new HttpResponse({
status: options.status || 200,
body: new Blob([JSON.stringify(options.body, null, 2)], {
type: 'application/json',
}),
url: request.url,
})
).pipe(delay(options.delay || 1000));
}
/**
* Returns a mocking handler for an HTTP request if configured and null otherwise.
* @param {HttpRequest} request The request to be mocked.
*/
getMockHandler({ method, url }: HttpRequest<unknown>) {
const methodHandlers = this.handlers[method] || [];
// Check if the current request's URL ends with the URL of a handler
for (const handlerUrl in methodHandlers) {
if (url.endsWith(handlerUrl)) {
return methodHandlers[handlerUrl];
}
}
return null;
}
}
开发工具中发生了什么
任何帮助都将不胜感激。干杯 responseType:'blob'尝试删除此内容并添加'json'谢谢您的回复,我尝试了这么做,但不幸的是它没有起作用。您能说出从backed()得到的信息并添加响应吗。。。。。。。如果您不知道chrome或搜索引擎中的确切格式类型,请访问此url
import { HttpRequest } from '@angular/common/http';
import { MockResponseOptions } from '../mock.types';
/**
* Returns mock HTTP response configuration for cases request
* @param {HttpRequest} request The request to be mocked.
*/
export function handleCasesRequest(
request: HttpRequest<unknown>
): MockResponseOptions {
// POST data is a JSON-encoded string in request.body
// let data = { data: "test returned" };
console.log('mock response triggered!');
const data = [
{
item: 1
},
{
item: 2
},
{
item: 3
}
];
return {
body: { output: `${JSON.stringify(data)}` },
};
}
import { actionButtonTypes } from './../../models/enums/actionButtonEnum';
import { Component, OnInit } from '@angular/core';
import * as env from "../../environments/environment"
import { handleCasesRequest } from "../../../../../libs/abf-api-mock/src/lib/responses/cases"
import { HttpClient } from '@angular/common/http';
import { delay, map } from 'rxjs/operators';
@Component({
selector: 'abf-lease-contract-overview',
templateUrl: './lease-contract-overview.component.html',
styleUrls: ['./lease-contract-overview.component.scss']
})
export class LeaseContractOverviewComponent implements OnInit {
uploadIconText = actionButtonTypes.Upload;
constructor(private http: HttpClient) { }
response: any;
private async fetchData() {
this.response = "";
this.response = await this.http
.get("http://localhost:4200/cases", { responseType: 'blob' })
.pipe(
map(response => {
console.log('dit is de response', response)
return response;
})
).subscribe(data => {
return data;
}
)
}
ngOnInit(): void {
this.fetchData();
}
}