Как прочитать файл json в Angular 7 с помощью http-модуля?

#json #angular #http

#json #angular #http

Вопрос:

Прочитать файл JSON в Angular 7

Я пишу простую программу для вывода массива данных из файла json в браузер.

Когда я пытаюсь прочитать файл json, я получаю сообщение об ошибке: не удается прочитать свойство ‘code’ undefined.

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>
  

Комментарии:

1. При рассмотрении ответов убедитесь, что вы выбрали самый быстрый ответ. Я не прошу вас отмечать мой, но я вижу вас здесь как нового пользователя! Просто внимание

Ответ №1:

Здесь:

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

ng-repeat это синтаксис AngularJS. Вы хотите

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

Комментарии:

1. Большое вам спасибо! Я думал об этой проблеме 2 дня ))

Ответ №2:

Вам нужно использовать ngFor with Angular вместо ng-repeat синтаксиса Angularjs,

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

Ответ №3:

В 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>