Peter Weeks
Peter Weeks

Reputation: 310

Trying to load data from a json file via http request

So I have this Angular app, and right now we're just loading data from a json file until my friends get the database up and running, but I"m having an issue: the data never seems to load. Can anybody look at my code and tell me what I'm doing wrong? Here's my data service code:

export class DataService {
  public positionsData: Position = {
      id: 'empty',
      name: 'empty',
      title: 'empty',
      routing: 'empty',
      email: 'empty',
      children: []
  };
  public loaded = false;

  constructor(private http: HttpClient) {
    setTimeout(() => {this.loadData}, 15);
  }

  loadData(): void {
    this.http.get<Position>('./sponsorview_data_4_22.json').subscribe( (updatedPositions: Position) => { this.positionsData = updatedPositions; this.loaded = true;});
  }

and here's the component where I need that data:

ngOnInit(): void {
    this.authSubscription = this.accountService.getAuthenticationState().subscribe(account => (this.account = account));
    if(!this.dataService.loaded) {
        this.datasource = this.dataService.getPositions();
        setTimeout(() => {this.loadDatasource();}, 370)
    }

}

  loadDatasource(): void {
    console.log('one round in loadDatasource');
    if(this.dataService.loaded) {
        console.log("data loaded and initialized");
        this.datasource = this.dataService.getPositionsToDepth(this.dataService.getPositions(), 3);
        this.rootViewNodeId = this.datasource.id;
        this.focusedNodeId = this.datasource.id;setTimeout(this.loadDatasource, 37);

    } else {
        setTimeout(() => {this.loadDatasource()}, 370)
        console.log("data not yet loaded");
    }

  }

Upvotes: 0

Views: 148

Answers (1)

saucecodee
saucecodee

Reputation: 109

I don't think you should be calling an Http request on a JSON without a server. Alternatively, you can get the JSON data directly like this.

this.positionsData = JSON.parse('./sponsorview_data_4_22.json');

Upvotes: 2

Related Questions