partie de ma service.spec.ts est ci-dessous:La valeur du tableau JSON affiche undefiend après l'avoir converti en chaîne
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"
});
}))
La valeur de mockResponse est la suivante:
const mockResponse = [{"name": "aditya"}, {"name": "xyz"}];
Journaux:
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
Note: Ce '[{"name":"aditya"},{"name":"xyz"}]'
est une chaîne! Comme je l'ai converti en JSON.stringify(mockResponse)
, si je ne l'aurais pas utilisé alors il affiche Object: [....], Object: [....]
.
Je suivais ce https://angular.io/api/http/ResponseOptions Ici, il utilise 'body' mais quand dans la réponse' ses _body'.Does affecte-t-il? – Aditya
Selon (1) 'result' n'est pas un tableau, mais un objet de réponse, qui a une propriété' _body', qui a une chaîne JSON. Donc (2) devrait être: 'JSON.parseJSON (result._body) [0]' –