gpt4 book ai didi

javascript - 类型 'results' 上不存在属性 'AppComponent'

转载 作者:行者123 更新时间:2023-11-29 19:02:43 25 4
gpt4 key购买 nike

我试图从 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 变量在类中是否存在/已初始化,然后再在任何方法中使用它。

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'];

});
}
}

关于javascript - 类型 'results' 上不存在属性 'AppComponent',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45697739/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com