0

This should be the simplest thing. I have a component that calls a service that imports a local JSON directly (see Import JSON directly with Angular 7) It reads the JSON contents fine, but the pages property is undefined. I think I set everything up based on the StackBlitz in that link, there doesn't seem to be much to it. There isn't any HTML yet, this is all just via the console. It's in app.component.html.

Reading local json files json.service.ts:14

[{…}]0: {name: "Home"}length: 1__proto__: Array(0) json.service.ts:15

undefined home.component.ts:31

json.service.ts:

import { Injectable } from '@angular/core';
import SampleJson from '../assets/SampleJson.json';

export interface JsonInterface {
  name: any;
}

@Injectable()
export class JsonService {
  ngOnInit() {
   console.log('Reading local json files');
   console.log(SampleJson);
  }
}

home.component.ts:

import { JsonService, JsonInterface } from '../json.service';
import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})

export class HomeComponent implements OnInit {
  constructor(service: JsonService) {
    service.ngOnInit();
  };

  @Input() pages: JsonInterface;

  ngOnInit() {
    console.log(this.pages);
  }
}

Sample.json

{ "name":"Home" }
Community
  • 1
  • 1
crinkledMap
  • 1,192
  • 1
  • 8
  • 8

2 Answers2

1

If I understand your log correctly, it works as expected:

  constructor(service: JsonService) {
    service.ngOnInit();
  };

You request the service and you get an instance. Then you call ngOnInit:

  ngOnInit() {
   console.log('Reading local json files');
   console.log(SampleJson);
  }

Now it logs the "reading…" and the content of your json file.

  ngOnInit() {
    console.log(this.pages);
  }

Then you log this.pages which is empty. You never filled it. You never did anything with your service or the data loaded in your service.

I think what you want is something like this

export class JsonService {
  getPages() { return SampleJson; }
}

and in your component:

  constructor(private service: JsonService) {}
  ngOnInit() {
    this.pages = this.service.getPages();
    console.log(this.pages);
  }

The sample code is not tested but I think you've got the point.

Christoph Lütjen
  • 5,403
  • 2
  • 24
  • 33
0

The problem is with pages. You have inly declared 'pages' as 'JsonInterface' which is only the type of 'pages' but never initialized with any value so it is undefined.. you need to write a function in Service as the above answer by @Christoph .

I hope you understand why this error occured and If you are not inputting a value to 'pages' from html you don't need to declare it as '@Input'.

Akhi Akl
  • 3,795
  • 1
  • 15
  • 26