TypeError:无法读取未定义的属性“类”

时间:2018-07-18 12:49:22

标签: html css angular typescript httpclient

我是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()的行之后,仍然出现相同的错误。

2 个答案:

答案 0 :(得分:0)

我假设在从get获取数据之前先渲染div,然后posts仍未定义。 将*ngIf="posts"添加到div中,以便在未定义posts时不会呈现它。

答案 1 :(得分:0)

组件初始化时,帖子仍未定义。 安全的导航操作员应解决您的问题

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