簡體   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