【问题标题】:JSON service returning undefined property with Angular 7JSON服务使用Angular 7返回未定义的属性
【发布时间】:2019-05-09 15:22:18
【问题描述】:

这应该是最简单的事情了。我有一个组件调用直接导入本地 JSON 的服务(请参阅Import JSON directly with Angular 7) 它可以很好地读取 JSON 内容,但 pages 属性未定义。我想我在该链接中基于 StackBlitz 设置了所有内容,似乎没有太多内容。还没有任何 HTML,这一切都只是通过控制台。它在 app.component.html 中。

读取本地json文件json.service.ts:14

[{…}]0: {name: "Home"}length: 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" }

【问题讨论】:

  • 你能发布html吗?
  • @AkhiAkl 没有。只是 app.component.html 中的 。还有

    Home Works!

    在 home.component.html

标签: json angular typescript angular7


【解决方案1】:

如果我正确理解您的日志,它会按预期工作:

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

您请求服务并获得一个实例。然后你调用 ngOnInit:

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

现在它会记录“正在读取...”和您的 json 文件的内容。

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

然后你记录 this.pages 是空的。你从来没有填过它。您从未对您的服务或服务中加载的数据进行任何操作。

我想你想要的是这样的

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

在你的组件中:

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

示例代码没有经过测试,但我认为你已经明白了。

【讨论】:

    【解决方案2】:

    问题在于页面。您已将“pages”声明为“JsonInterface”,这只是“pages”的类型,但从未使用任何值初始化,因此未定义..您需要在 Service 中编写一个函数,作为@Christoph 的上述答案。

    我希望您了解为什么会发生此错误,如果您没有从 html 向“页面”输入值,则无需将其声明为“@Input”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-05
      • 2019-08-09
      相关资源
      最近更新 更多