繁体   English   中英

属性“结果”在类型“ AppComponent”上不存在

[英]Property 'results' does not exist on type 'AppComponent'

我正在尝试从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'];

    });
  }
}

这是因为Typescript编译器会在任何方法中使用results变量之前,先检查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'];

    });
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM