财产'结果'类型' AppComponent'上不存在

时间:2017-08-15 16:59:07

标签: javascript json angular

我正在尝试从json响应中获取results字段但是我收到错误Property 'results' does not exist on type 'AppComponent

import { Component } from '@angular/core';

//in place where you wanted to use `HttpClient`
import { HttpClient } from '@angular/common/http';



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

export class AppComponent {
  title = 'app';

  // Inject HttpClient into your component or service.
  constructor(private http: HttpClient) {}
  ngOnInit(): void {

    // Make the HTTP request:
    this.http.get('assets/api/list.json').subscribe(data => {

      // Read the result field from the JSON response.
      this.results = data['results'];

    });
  }
}

2 个答案:

答案 0 :(得分:3)

这是因为在任何方法中使用它之前,Typescript编译器会在类中检查results变量是否存在/初始化。

export class AppComponent {
  title = 'app';
  results: any[]; //define it here

  // Inject HttpClient into your component or service.
  constructor(private http: HttpClient) {}
  ngOnInit(): void {

    // Make the HTTP request:
    this.http.get('assets/api/list.json').subscribe(data => {

      // Read the result field from the JSON response.
      this.results = data['results'];

    });
  }
}

答案 1 :(得分:0)

有时 ['results'] 会记录相同的错误。 (也许适用于较新的 angular/ts 版本)

 this.http.get(url).subscribe((data:any) => {

  // Read the result field from the JSON response.
  //this.results = data.results;
  this.results = data['results'];
相关问题