-1

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;
 }
}
eli
  • 313
  • 3
  • 6
  • 17
  • First, try to console.log the data itself inside the request function to check what you get in real in your response. – Ziyaddin Sadigov Oct 12 '17 at 10:16
  • @ZiyaddinSadigov inside the request I get the JSON object – eli Oct 12 '17 at 10:18
  • 1
    @ZiyaddinSadigov that will only confuse them further, as they *do* have the response inside the callback. The point is that **this is asynchronous**. – jonrsharpe Oct 12 '17 at 10:18
  • @jonrsharpe I agree. Missed that point. – Ziyaddin Sadigov Oct 12 '17 at 10:21
  • @eli as jonrsharpe stated, you need to add the last two lines into request function, because these last two lines are working in synchronous mode but your function is in asynchronous mode. – Ziyaddin Sadigov Oct 12 '17 at 10:23
  • @ZiyaddinSadigov actually, I put the return statement outside the request function, because I thought the service wouldn't return anything if I left it inside the request – eli Oct 12 '17 at 10:44

1 Answers1

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.

Ali Turab Abbasi
  • 1,103
  • 8
  • 22