简体   繁体   English

通过ngfor从Angular 5的本地json文件中获取特定数组

[英]Getting specific array from local json file in angular 5 via ngfor

I've local json file having arrays. 我有数组的本地json文件。 I want to get specific array in html document although i can get it in javascript using for loop but how to show this in html document. 我想在html文档中获取特定的数组,尽管我可以使用for循环在javascript中获取它,但是如何在html文档中显示出来。

for (let i = 0; i < data.static_data.model.length; i++) {
  console.log(data.static_data.model[i]);
}

This works but problem is in HTML, it's not displaying. 这可行,但问题出在HTML中,但未显示。

<li *ngFor="let model of data; let i = index"> {{ model.static_data.model[i] }}</li>

It also don't show any error in console. 它还不会在控制台中显示任何错误。 Any help/hint will be appreciated. 任何帮助/提示将不胜感激。 If there is better way to do this, Kindly share. 如果有更好的方法,请分享。

Firstly consume the JSON file using HttpClient and subscribe it and then push the contents into an array. 首先使用HttpClient使用JSON文件并进行订阅,然后将内容推入数组。

The AppModule AppModule

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 { }

The AppComponent AppComponent

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));
     }
}

Your HTML 您的HTML

<li *ngFor="let model of YourModel;">model.someProperty</li>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM