gpt4 book ai didi

javascript - JSON数组转成字符串后显示undefined

转载 作者:行者123 更新时间:2023-12-01 03:18:13 25 4
gpt4 key购买 nike

我的 service.spec.ts 的一部分如下:

service.spec.ts

it('should mock the http requests', inject([Service, MockBackend], (service, mockBackend) => {
let result:any;
mockBackend.connections.subscribe((connection) => {
connection.mockRespond(new Response(new ResponseOptions({

body: JSON.stringify(mockResponse),

})));
});
service.getGoogle().subscribe((heroes: any) => {
result = heroes;
console.log('1', result);
console.log('2', result[0]); //Logs shows this as undefined!!I need to print here "aditya"
});
}))

mockResponse的值如下:

const mockResponse = [{"name":"aditya"},{"name":"xyz"}];

日志:

LOG: 'Inside service'
LOG: '1', Response{_body: '[{"name":"aditya"},{"name":"xyz"}]', status: null, ok: false, statusText: null, headers: null, type: null, url: null}
LOG: '2', undefined
Other method
√ should mock the http requests

注意:'[{"name":"aditya"},{"name":"xyz"}]' 这是一个字符串!由于我已将其转换为 JSON.stringify(mockResponse),如果我没有使用它,那么它会显示为 Object: [....], Object: [.... ]

最佳答案

不知道你的问题是什么。该代码似乎正在执行您所要求的操作。

这个:

JSON.stringify(mockResponse),

将数组转换为字符串。然后,您可以将该字符串设置为带有键 body 的对象的值。并归还它。

您的订阅方法正在接收整个 Response 对象,尽管从变量名称来看,我们假设您期望的是 Heroes 对象。 (如果您将类型设置为 any 以外的类型,Typescript 将捕获此类错误)

现在,当您记录 result 时,它会记录您刚刚收到的 Result 对象。其中包括持有弦化物体的 body 。

result[0] 为空,因为 result 不是数组。

我想你想要:

service.getGoogle().subscribe((result: any) => {
heroes = JSON.parse(result._body)

// heroes is now an array you started with
// heroes[0] == {"name":"aditya"}
// heroes[1] == {"name":"xyz"}

关于javascript - JSON数组转成字符串后显示undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45394063/

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