2017-07-29 69 views
0

部分我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: [....]

+0

我這個https://angular.io/api/http/ResponseOptions這是使用'body'但是當在響應其'_body'.Does以下它影響? – Aditya

+0

根據(1)'result'不是一個數組,而是一個響應對象,它有一個'_body'-屬性,它有一個JSON字符串。所以(2)應該是:'JSON.parseJSON(result._body)[0]' –

回答

2

不知道你的問題是什麼。代碼似乎在做你在問什麼。

此:

JSON.stringify(mockResponse), 

打開的陣列成一個字符串。然後您使用鍵body將該字符串作爲對象的值。並返回它。

您的訂閱方法正在接收整個Response對象,不過從變量名稱來看,我們假設您期待Heroes對象。 (如果將類型設置爲除any以外的其他類型,則Typescript將捕獲此類錯誤)

現在,當您登錄result時,它會記錄您剛收到的Result對象。其中包括持有您的字符串化對象的身體。

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"} 
+0

實際上,我在這裏傳遞了硬編碼的響應,這是JSON.So我創建了一個JSON數組。創建它之後,我將它作爲一個響應,爲我的模擬請求提供服務。然後想在控制檯中顯示此響應並對其進行測試。 – Aditya

+0

您在控制檯中顯示您的回覆:'Response {_body:'[{「name」:「aditya」},{「name」:「xyz」}]',status:null,ok:false,statusText:null ,header:null,type:null,url:null}' –

+0

我想顯示「name」:「aditya」作爲數組的第一個元素,我該怎麼做? – Aditya