如何通过使用http模块在Angular 7中读取文件json?

时间:2019-04-20 19:03:43

标签: json angular http

在Angular 7中读取JSON文件

我正在编写一个简单的程序,以将数据数组从json文件输出到浏览器。

当我尝试读取json文件时,出现错误: 无法读取未定义的属性“代码”。

app.module.ts:

import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    RouterModule.forRoot(appRoutes),
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts:

import { Component } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

   countries: any;

   constructor(private http : HttpClient) { }

   ngOnInit(){
       this.http.get("...path to json file...")
       .subscribe((data) => this.displaydata(data));
   }

   displaydata(data) {this.countries = data;}
}

app.component.html:

<table>
<tr >
  <th>ID</th >
  <th>code</th >
  <th>name</th >
  <th>population</th >
</tr >
  <tr ng-repeat="country in countries">
  <td>{{country.code}}</td>
  <td>{{country.name}}</td>
  <td>{{country.population}}</td>
</tr>
</table>

3 个答案:

答案 0 :(得分:1)

这里:

  <tr ng-repeat="country in countries">

ng-repeat是AngularJS语法。您要

  <tr *ngFor="let country of countries">

答案 1 :(得分:1)

您需要对Angular使用 ngFor ,而不是Angularjs语法 ng-repeat

 </tr >
  <tr *ngFor="let country of countries">
  <td>{{country.code}}</td>
  <td>{{country.name}}</td>
  <td>{{country.population}}</td>
</tr>

答案 2 :(得分:0)

在Angular 7中没有ng-repeat,请改用*ngFor

</tr >
  <tr *ngFor="let country of countries">
  <td>{{country.code}}</td>
  <td>{{country.name}}</td>
  <td>{{country.population}}</td>
</tr>