【问题标题】:TypeError: Cannot read property 'Classes' of undefinedTypeError:无法读取未定义的属性“类”
【发布时间】:2018-07-18 12:49:21
【问题描述】:

我是 Angular 框架和 TypeScript 的新手。我正在尝试在this tutorial 之后发出 GET 请求。它对我有用,但是当我尝试发出另一个 GET 请求时,如下所示,我收到下一个错误:

AppComponent.html:7 ERROR TypeError: Cannot read property 'Classes' of undefined
at Object.eval [as updateRenderer] (AppComponent.html:7)
at Object.debugUpdateRenderer [as updateRenderer] (core.js:14735)
at checkAndUpdateView (core.js:13849)
at callViewAction (core.js:14195)
at execComponentViewsAction (core.js:14127)
at checkAndUpdateView (core.js:13850)
at callWithDebugContext (core.js:15098)
at Object.debugCheckAndUpdateView [as checkAndUpdateView] (core.js:14635)
at ViewRef_.detectChanges (core.js:11619)
at eval (core.js:5918)

我有这个 app.component.ts:

import { Component, onInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  posts: any;
  Classes: string;

  readonly ROOT_URL = 'http://localhost:8080/[path]';

  constructor(private http: HttpClient){
  }
  getPosts() {
      this.posts = this.http.get(ROOT_URL + "/getClasses");
  }
  }

在 app.component.html 中:

<button (click)="getPosts()">Get Posts</button>
<div>
  {{ posts.Classes | json }}
  </div>

我尝试获取的 JSON 是:

{"Classes":["Element1","Element2","Element3"]}

在我添加了调用 getPosts() 的行之后,我仍然得到同样的错误。

【问题讨论】:

  • 你在哪里调用 getPosts()?

标签: html css angular typescript httpclient


【解决方案1】:

我假设 div 在您从 get 获取数据之前渲染,然后 posts 仍然未定义。 将 *ngIf="posts" 添加到 div 中,这样如果 posts 未定义,则不会呈现。

【讨论】:

  • 很好。但是 OP 似乎没有在他的代码中的任何地方调用 getPosts() 方法。
  • 我希望我能多次支持这个答案,因为它刚刚解决了我在单元测试中遇到的问题
【解决方案2】:

当组件初始化时,posts 仍然是未定义的。 安全导航操作员应该可以解决您的问题

<div> {{ posts?.Classes | json }} </div>

【讨论】:

    猜你喜欢
    • 2021-11-20
    • 2021-05-13
    • 1970-01-01
    • 1970-01-01
    • 2020-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多