0

Read JSON file in Angular 7

I am writing a simple program to output an array of data from a json file to a browser.

When I try to read a json file, I get an error: Cannot read property 'code' of 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
  • While considering answers make sure you choose the fastest response. I am not asking you to mark mine, but i see you as a new user here! Just a heads up Commented Apr 20, 2019 at 19:53

3 Answers 3

1

Here:

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

ng-repeat is AngularJS syntax. You want

  <tr *ngFor="let country of countries">
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! I thought about this problem for 2 days ))
1

You need to use ngFor with Angular instead of ng-repeat which is Angularjs syntax,

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

Comments

0

In Angular 7 there is no ng-repeat, use *ngFor instead

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.