这应该是最简单的事情。我有一个组件可以调用直接导入本地JSON的服务(请参见Import JSON directly with Angular 7) 它可以很好地读取JSON内容,但是 pages 属性未定义。我想我在该链接中基于StackBlitz进行了所有设置,似乎并没有太多内容。还没有任何HTML,仅通过控制台即可。在app.component.html中。
读取本地json文件json.service.ts:14
[{…}] 0:{name:“ Home”}长度:1__proto__:Array(0)json.service.ts:15
未定义的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" }
答案 0 :(得分:1)
如果我正确理解了您的日志,则可以正常运行:
constructor(service: JsonService) {
service.ngOnInit();
};
您请求服务并获得一个实例。然后调用ngOnInit:
ngOnInit() {
console.log('Reading local json files');
console.log(SampleJson);
}
现在,它记录“正在读取...”和json文件的内容。
ngOnInit() {
console.log(this.pages);
}
然后您将记录此页面为空。你从来没有填过它。您从未对服务或服务中加载的数据进行任何操作。
我认为您想要的就是这样
export class JsonService {
getPages() { return SampleJson; }
}
以及您的组件中
constructor(private service: JsonService) {}
ngOnInit() {
this.pages = this.service.getPages();
console.log(this.pages);
}
示例代码未经测试,但我认为您已经明白了。
答案 1 :(得分:0)
问题出在页面上。您已经将'pages'声明为'JsonInterface',这只是'pages'的类型,但从未用任何值初始化,因此它是未定义的。.您需要在Service中编写一个函数,就像@Christoph给出的上述答案一样。>
我希望您能理解为什么会发生此错误,并且如果您不从html向'pages'输入值,则无需将其声明为'@Input'。