部分我service.spec.ts的後undefiend的值低於:JSON數組顯示器將其轉換成字符串
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: [....]
。
我這個https://angular.io/api/http/ResponseOptions這是使用'body'但是當在響應其'_body'.Does以下它影響? – Aditya
根據(1)'result'不是一個數組,而是一個響應對象,它有一個'_body'-屬性,它有一個JSON字符串。所以(2)應該是:'JSON.parseJSON(result._body)[0]' –