我的本地json文件有数组。我想在html文档中获取特定的数组,虽然我可以在javascript中使用for循环但是如何在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>
它也不会在控制台中显示任何错误。任何帮助/提示将不胜感激。如果有更好的方法,请分享。
答案 0 :(得分:0)
首先使用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>