简体   繁体   中英

getting json data into an array angular2

I am not sure what i am missing from my code but currently i am not presented with any errors when i run it but i am also not seeing the results that i am expecting. I have a json file that i am loading into an array and would like to loop through that array and display parts of its data onto the page.

Here is what i have so far:

Service file

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

@Injectable()

export class AddressDataService{
    addressData: Array<any>;

    constructor(private http:Http){ }
    getAddressData(){
        return this.http.get('./api/addressData.json')
                 .map((res:Response) => res.json());
    }
}

JSON File

[{
    "type": "home",
    "id": 1
}, {
    "type": "apartment",
    "id": 2
}, {
    "type": "homeless",
    "id": 3
}]

Component File

import { Http } from '@angular/http';
import { AddressDataService } from './address.service';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

@Component({
  selector: 'my-app',
  templateUrl: '....',
  styleUrls: ['./styles.css'],
  providers: [AddressDataService]
})

constructor(private addressDataService: AddressDataService) {}
  addressData = [];
  getAddressData() {
  this.addressDataService.getAddressData()
                   .subscribe(data => this.addressData = data);
}

HTML File

<div *ngFor="let addressDetail of addressData">
    {{addressDetail.type}}
</div>

Am i doing this the right way?

You need to call your getAddressData for example in your OnInit , I assume you want to fetch the data when navigated to page.

So:

ngOnInit() {
  this.getAddressData();
}

When this is handled, you will face another issue. Http-requests don't allow relative paths, so

return this.http.get('./api/addressData.json')

will cause an error, you need to replace the dot in your "url" with the actual complete path for the json file, starting from the top level folder.

In your component file:

.subscribe(
      data => {
        const helperArray = [];
        for (let key in data) {
          helperArray.push(data[key]);
        }
      }
);

Something in your component class needs to call your getAddressData method. Either the constructor, or a better option is to implement OnInit and call it from there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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