javascript - 无法将 JSON 结果绑定(bind)到组件变量

标签 javascript angular ecmascript-6

我正在尝试一个必须从 JSON 文件中提取数据的简单组件。我几乎从生成的 Fountain 应用程序复制功能,但由于某种原因我无法获得所需的结果。我有一个像这样的组件:

import {Component, Inject} from "@angular/core";
import {Http} from '@angular/http';

@Component({
  selector: 'body-selector',
  template: require('./body.html')
})

@Inject(Http)

export class BodyComponent {
  constructor(http: Http) {
    this.http = http;
    this.getText('app/texts/main.json').subscribe(result => {
    console.log(result);
    this.texts = result;
  });
  console.log(this.texts);
}
  getText(url) {
    return this.http.get(url).map(response => response.json());
  }
}

在第一个 console.log 上,我有 [Object object] [Object object] [Object object],这是正确的,因为我在 JSON 中有三个条目。然而,在第二个我有未定义,这在浏览器中变成了一个错误。

Error in ./BodyComponent class BodyComponent - inline template:3:6 caused by: Cannot read property 'title' of undefined

我正在查看喷泉应用程序生成的示例,但我不明白我做错了什么。

最佳答案

您有多个问题:

  • 第一个 console.log 位于回调内部,其中 this.texts 刚刚被设置。然而,第二个在回调之外,所以它不会。因此,您总是会看到 undefined,因为...

  • ...您从未为 this.texts 设置默认值,并且您的模板显然没有任何例如*ngIf 来处理它为 nullundefined,从而在调用回调之前导致错误。

下面是您的代码,重构为以空的 this.texts 开头(假设它应该是一个数组;请适应口味)并简化 Http 的注入(inject)。另请注意注释,并且我使用 templateUrl 来避免 requireOnInit 在组件生命周期稍后触发 HTTP 调用而不是在构造函数中执行它。

import {Component, OnInit} from '@angular/core';  // note consistent quotes
import {Http} from '@angular/http';

@Component({
  selector: 'body-selector',
  templateUrl: './body.html',
})
export class BodyComponent implements OnInit {
  texts: any[] = [];  // start with an empty array

  constructor(private http: Http) { }  // inject Http here, no need to assign to this

  ngOnInit() {
    this.http
      .get('app/texts/main.json')
      .map(response => response.json())
      .subscribe(result => {
        console.log(result);  // only log *inside* the callback
        this.texts = result;
      });
    // outside the callback, the HTTP call hasn't yet finished
  }

}

您还可以通过在 HTML 中添加 ngIf 来解决此问题,以防止在数据加载之前加载元素。

<div class="main-container" *ngIf="texts">
  ...
</div>

我强烈建议您阅读基本的 Angular 2 教程来掌握这些内容,请参阅例如the Tour of Heroes .

关于javascript - 无法将 JSON 结果绑定(bind)到组件变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40639818/

相关文章:

javascript - ionic 2 : "WARNING: sanitizing unsafe URL value" error

javascript - 如何从 Angular 中的子路由组件访问父组件属性?

javascript - 反序列化可能的子项,它们可能具有需要反序列化的属性

javascript - IE 卡在 jQuery 代码上

javascript - 检测 DIV 的 HTML 和 CSS 并进行更改以使其与同级 DIV 一起滚动

javascript - iOS - css/js - 覆盖滚动但防止 body 滚动

Angular:从另一个指令获取主机上一个指令实例的引用

javascript - 使用 for 循环和 setTimeout 在 ES6 中修改 React Elements

javascript - 在 React 中设置 jsx 元素的样式

javascript - 同时运行 2 个 JavaScript 脚本