Angular service that makes HTTP request

时间:2017-10-12 10:12:49

标签: angular typescript

I have this Angular 4 service that makes a HTTP request and returns the data. However, when I log the result in console I get undefined.

This is my service:

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;
 }
}

1 个答案:

答案 0 :(得分:1)

The reason you get Undefined is that you are using console outside the arrow function. Do remember that this is an asynchronous call and at the time you're using console.log, there is no data in it.

Try using console.log inside the function and you'll get your result.