eli
eli

Reputation: 313

How to call service in component?

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();


 }

}

Upvotes: 2

Views: 23392

Answers (3)

yaya
yaya

Reputation: 8243

  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.

Upvotes: 2

Mohamed Ali RACHID
Mohamed Ali RACHID

Reputation: 3297

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

Upvotes: 2

sz tech
sz tech

Reputation: 349

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.

Upvotes: 1

Related Questions