发出HTTP请求的角度服务

发出HTTP请求的角度服务

问题描述:

我有这个发出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

未定义的原因是,您使用的是箭头功能外控制台。请记住,这是一个异步调用,并且在您使用console.log时,其中没有数据。

尝试使用console.log内的函数,你会得到你的结果。