错误TypeError:无法读取未定义的属性“命令”

时间:2020-10-28 21:41:24

标签: javascript angular typescript http

我想将来自API的数据显示为我制作的angular项目中的前端,但出现错误..我在互联网上进行了大量搜索,但无法获得想要的结果。我很高兴您可以为此提供帮助。

错误

vendor.js:16522 ERROR TypeError: Cannot read property 'fiats' of undefined
    at FiatsComponent_Template (main.js:219)
    at executeTemplate (vendor.js:19621)
    at refreshView (vendor.js:19490)
    at refreshComponent (vendor.js:20637)
    at refreshChildComponents (vendor.js:19296)
    at refreshView (vendor.js:19540)
    at refreshEmbeddedViews (vendor.js:20591)
    at refreshView (vendor.js:19514)
    at refreshComponent (vendor.js:20637)
    at refreshChildComponents (vendor.js:19296)

API服务

const API_URL = 'https://api.bitpanda.com/v1/masterdata';

@Injectable({
  providedIn: 'root',
})
export class ApiService {
  constructor(private http: HttpClient) {}

  getDatafromApi() {
    return this.http.get<Attributes[]>(API_URL);
  }
}

fiats.compontent.ts

export class FiatsComponent implements OnInit {
  apiData: Attributes[];
  apiDataA: Attributes;

  constructor(private apiService: ApiService) {}

  ngOnInit() {
    this.getDatafromAPI();
    console.log('? ', this.getDatafromAPI()); //undefined
  }

  getDatafromAPI() {
    this.apiService.getDatafromApi().subscribe((data) => {
      this.apiData = data;
      console.log('? ', data); ////data
    });
  }
}

fiats.component.html

<div *ngFor="let A of apiDataA.fiats">
  <div *ngFor="let b of A.attributes">
    <p>{{ b.name }}</p>
  </div>
</div>

2 个答案:

答案 0 :(得分:0)

问题是您的模板第一次渲染apiDataA时未定义。您从api中检索到的数据将稍后返回。

您可以使用* ngFor循环中的封闭容器轻松解决此问题:

<ng-container *ngIf="apiDataA">
...
</ng-container>

您还可以考虑使用Angulars async pipe

答案 1 :(得分:0)

好像您将返回的数据设置为apiData而不是apiDataA。您的数据也位于嵌套数组中,只是缺少一个级别。

  getDatafromAPI() {
    this.apiService.getDatafromApi().subscribe((data) => {
      this.apiDataA = data;
      console.log('? ', data); ////data
    });
 }

<ng-container *ngIf="apiDataA">
  <div *ngFor="let A of apiDataA.attributes">
    <div *ngFor="let b of A.fiats">
      <p>{{ b.name }}</p>
    </div>
  </div>
</ng-container>