Reputation: 313
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
Reputation: 8243
constructor(private myService: MyService){
@NgModule({
...
providers: [MyService]})
3 now you can use your service with this.myService
in your component.
Upvotes: 2
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
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