2

I have a service that makes a http request and returns the response. I want to use that response in my component and display parts of it in the screen, but it's not working. I don't get any errors in console, but there's nothing showing on screen.

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;
 path:'/assets/MENU.json';

getMenu():any{
    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;
      });        

 }
} 

This is my component:

import { Component, OnInit } from '@angular/core';
import { MenuService } from '../menu.service';

@Component({
moduleId: module.id,
templateUrl: 'home.component.html',
styleUrls: ['home.component.css']
})

export class HomeComponent implements OnInit {


constructor(private menuService: MenuService) {

}
nodes:any;

get(): void {
  this.nodes = this.menuService.getMenu();

}

ngOnInit(): void {
 this.get();


 }

}

3 Answers 3

2

first , update the service returne value to Observable :

getMenu():Observable<any>{
    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.json();
      });        
}

u can get the menu in your component like that :

get(): void {
  this.menuService.getMenu().subscribe( 
     result => {
         this.nodes = result; 
     }
     error => console.log(error);
  );
}
Sign up to request clarification or add additional context in comments.

3 Comments

which screen ? do u mean the console ?
No, the browser
is it necessary to call service in module and component both. Suppose i have to use a common service in all components then do i have to add that service in all the components?
2
  1. in component's constructor, add an argument with type of your service:
constructor(private myService: MyService){
  1. register service in module declaration:
@NgModule({
...
providers: [MyService]})

3 now you can use your service with this.myService in your component.

Comments

1

You have to register it in your app module as well. Find your @NgModule and list the MenuService Class in your providers field.

Like this:

@NgModule({
    declarations: [
        AppComponent,
        HomeComponent
    ],
    imports: [
        bla,
        bla
    ],
    providers: [
        MenuService
    ],
    bootstrap: [AppComponent],
    schemas: []
})

The biggest problem is that you are not actually return anything in the getMenu method.

Try to do the following instead:

get(): void {
  this.menuService.getMenu().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+="]";
        const menu=JSON.parse(newValue);
        this.nodes = menu;
      });

}

And instead of getMenuService do this:

getMenu():any{
    return this.http.get('/assets/MENU.json');        

 }

It's strange that you not getting any errors though.

7 Comments

what is the difference between my answer and your updated answer ? :) @sz tech
Not much. I just realised that @eli may want to subscribe to the response as well. But your answer is also correct.
By the way, none of our answers is correct. I found the error updating my response now.
@eli try it now. The problem was that you haven't returned anything in your service.
@sztech Tried it. Got this error: Cannot read property 'subscribe' of undefined
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.