2017-10-12 180 views
-1

我有這個發出HTTP請求並返回數據的Angular 4服務。但是,當我將結果記錄在控制檯中時,我得到undefined發出HTTP請求的角度服務

這是我的服務:

import { Injectable } from '@angular/core'; 
import { HttpClient } from '@angular/common/http'; 
@Injectable() 
export class MenuService { 
constructor(private http: HttpClient) { 

} 
menu: any; 

getMenu(){ 
    this.http.get('/assets/MENU.json').subscribe(data => { 
     // Read the result field from the JSON response. 

     let newValue = JSON.stringify(data).replace('{"Node":', '['); 
     newValue = newValue.substring(0,newValue.length - 1); 
     newValue+="]"; 
     this.menu=JSON.parse(newValue); 


     }); 
     console.log(this.menu); 
     return this.menu; 
} 
} 
+0

首先,嘗試將console.log中的數據本身放在請求函數中,以檢查您在響應中實際得到的內容。 –

+0

@ZiyaddinSadigov裏面的請求我得到的JSON對象 – eli

+1

@ ZiyaddinSadigov只會進一步混淆他們,因爲他們*做*有迴應內的迴應。重點是**這是異步**。 – jonrsharpe

回答

1

未定義的原因是,您使用的是箭頭功能外控制檯。請記住,這是一個異步調用,並且在您使用console.log時,其中沒有數據。

嘗試使用console.log內的函數,你會得到你的結果。