[英]How to load json api data to html template in angular?
誰能幫我一個簡單的問題(我猜)。 我正在嘗試通過 Django 將表中的 json 文件顯示到 Angular 前端應用程序中。 我可以通過控制台記錄數據來查看數據,但是我似乎無法將數據輸入網頁。
我知道如何在 HTML 中顯示表格。 具體問題是從 API 獲取的對象沒有出現在 HTML 中。
組件.ts
import { AfterViewInit, ChangeDetectionStrategy, Component, OnDestroy, OnInit, ViewChild,
ViewEncapsulation } from '@angular/core';
import ApexChart from 'apexcharts'
import { ApexOptions } from 'ng-apexcharts';
import { FinanceService } from 'app/modules/admin/dashboards/finance/finance.service';
@Component({
selector: 'app-finance',
templateUrl: './finance.component.html',
styleUrls: ['./finance.component.scss'],
encapsulation : ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class FinanceComponent implements OnInit {
_stockData: any;
_portData: any;
_effData: any;
_calData: any;
_labels: any;
_table: any;
constructor(
private _financeService: FinanceService,
){
}
ngOnInit(): void {
this._financeService.getFinanceData()
.subscribe((res: any) => {
console.log(res);
this._stockData = res.stocks;
this._portData = res.port;
this._effData = res.eff;
this._calData = res.cal;
this._labels = res.labels;
this._table = res.table;
console.log(res.table);
this._prepareChartData();
},
(response) => {
// Re-enable the form
});
}
服務.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { catchError, switchMap } from 'rxjs/operators';
import { BehaviorSubject, of, Observable } from 'rxjs';
import { environment } from 'environments/environment';
@Injectable({
providedIn: 'root'
})
export class FinanceService {
/**
* Constructor
* @param {HttpClient} _httpClient
*/
constructor(private _httpClient: HttpClient){
}
// -----------------------------------------------------------------------------------------------------
// @ Public methods
// -----------------------------------------------------------------------------------------------------
/**
* get Finance Data
*/
getFinanceData(): Observable<any>{
return this._httpClient.get(environment.baseURL + 'apiurls/', {}).pipe(
switchMap((response: any) => {
return of(response);
})
);
}
}
模板.html
<div>
<p>{{_table.Percentage}}</p>
</div>
json(由 django API 提供)
{
"stocks":[],
"eff":[],
"port":[],
"cal":[],
"labels":[],
"table":{
"Percentage":{
"AD.AS":16.1,
"ASML.AS":15.67,
"AAPL":68.23
},
"Budget":{
"AD.AS":241.5,
"ASML.AS":235.05,
"AAPL":1023.45
},
"Closing":{
"AD.AS":25.22,
"ASML.AS":314.3,
"AAPL":129.04
},
"Number of stocks to buy":{
"AD.AS":10.0,
"ASML.AS":1.0,
"AAPL":8.0
},
"final":{
"AD.AS":252.0,
"ASML.AS":314.0,
"AAPL":1032.0
},
"final allocation":{
"AD.AS":15.77,
"ASML.AS":19.65,
"AAPL":64.58
},
"Diff":{
"AD.AS":-0.33,
"ASML.AS":3.98,
"AAPL":-3.65
}
}
}
要在 html 上顯示 json 數據,您可以使用json 管道
<pre>
{{ _table.Percentage | json }}
</pre>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.