[英]Getting specific array from local json file in angular 5 via ngfor
我有數組的本地json文件。 我想在html文檔中獲取特定的數組,盡管我可以使用for循環在javascript中獲取它,但是如何在html文檔中顯示出來。
for (let i = 0; i < data.static_data.model.length; i++) {
console.log(data.static_data.model[i]);
}
這可行,但問題出在HTML中,但未顯示。
<li *ngFor="let model of data; let i = index"> {{ model.static_data.model[i] }}</li>
它還不會在控制台中顯示任何錯誤。 任何幫助/提示將不勝感激。 如果有更好的方法,請分享。
首先使用HttpClient使用JSON文件並進行訂閱,然后將內容推入數組。
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
imports: [BrowserModule, FormsModule, HttpClientModule],
declarations: [AppComponent],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
import {Component} from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import {Observable} from 'rxjs/Rx';
@Component({
selector: 'my-app'
})
export class AppComponent implements ngOnInit {
public YourModel : any;
ngOnInit() : void
{
this.getJSONFromLocal().subscribe(
data => {
//Bind the data emitted by JSON file to model class here
this.YourModel = data;
},
error => console.error(`Failed because: ${error}`));
}
constructor(private httpClient: HttpClient) {}
public getJSONFromLocal(): Observable<any> {
return this.httpClient.get("./someLocalFile.json")
.catch((error:any) => console.log(error));
}
}
<li *ngFor="let model of YourModel;">model.someProperty</li>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.