3

I'm learning Angular, I want to display JSON data on HTML page. The error is Http failure during parsing in Angular. I don't know why please tell me my mistake and give me links how to display JSON data with several types

person.component.html

<ul>

 <li *ngFor="let address of addresses">FirstName:{{ persons.addresses.City }}</li>
</ul>

person.json

[{
        "Addresses": [{ 

        "AddressId":101,
        "AddressTypes":["permanent", "temporary", "careof", "native"],
        "Address-L1":"space", 
        "Address-L2":"a.b.road",
        "Locality":"airoli(east)",
        "City":"Mumbai", 
        "State":"Maharashtra",
        "Country":"India",
        "Postalcode":400027
     }],

 "ContactNumbers" : 
[
    {

            "ContactID": 1,
            "ContactType": "Home",
            "CountryCode": "+91",
            "RegionCode": "022",
            "Number":2656568965

    }]    

}]

person-list.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
// import 'rxjs/add/operator/do';  // for debugging

export class Address{
  AddressId:number;
  City:string=""; 

}
/**
 * This class provides the NameList service with methods to read names and add names.
 */
@Injectable()
export class PersonListService {

  /**
   * Creates a new NameListService with the injected HttpClient.
   * @param {HttpClient} http - The injected HttpClient.
   * @constructor
   */
  constructor(private http: HttpClient) {}

  /**
   * Returns an Observable for the HTTP GET request for the JSON resource.
   * @return {string[]} The Observable for the HTTP request.
   */

  get(): Observable<Address[]>{
    console.log("Inside the get service")
    return this.http.get('app/person/person.json')

                 // .do(data => console.log('server data:', data))  // debug
                    .catch(this.handleError);

  }

  /**
    * Handle HTTP error
    */
  private handleError (error: any) {
    // In a real world app, we might use a remote logging infrastructure
    // We'd also dig deeper into the error to get a better message
    const errMsg = (error.message) ? error.message :
      error.status ? `${error.status} - ${error.statusText}` : 'Server error';
    console.error(errMsg); // log to console instead
    return Observable.throw(errMsg);
  }
}

person.component.ts

@Component({
  moduleId: module.id,
  selector: 'sd-person',
  templateUrl: 'person.component.html',
  styleUrls: ['person.component.css']
})
export class PersonComponent implements OnInit {
  errorMessage: string;

addresses: Address[]=[];
constructor(public personListService:PersonListService){}
  ngOnInit() {
     // console.log(jwt.AuthConfig);
     this.getperson();
  }

  getperson(){

    this.personListService.get()
    .subscribe(
      addresses => this.addresses = addresses,
      error => this.errorMessage = <any>error
    );
    console.log(this.persons);
  }
 }
0

2 Answers 2

1

That is technically invalid JSON because of the trailing comma after "Mumbai"

It should be

[{"Addresses": [{ 
        "AddressId":101,
        "City":"Mumbai" 
         }]
}]

EDIT

Following the update, that is also invalid, as it needs to be wrapped in an object, like so:

{
    "Addresses": [{

        "AddressId": 101,
        "AddressTypes": ["permanent", "temporary", "careof", "native"],
        "Address-L1": "space",
        "Address-L2": "a.b.road",
        "Locality": "airoli(east)",
        "City": "Mumbai",
        "State":"Maharashtra",
        "Country": "India",
        "Postalcode": 400027
    }],

    "ContactNumbers": [{

        "ContactID": 1,
        "ContactType": "Home",
        "CountryCode": "+91",
        "RegionCode": "022",
        "Number": 2656568965

    }]

}

This will create a single object, containing 2 arrays: "Addresses", and "ContactNumbers"

Sign up to request clarification or add additional context in comments.

16 Comments

@VinitMapari There must be some other error in the JSON. Can you please edit your question to include the full JSON file?
@VinitMapari I've just updated the answer following your updated JSON
I have updated and check and please tell me error I think error in calling on html page tell me your opinion
@VinitMapari Yep, I updated my answer, please take a look. Anytime it mentions error in parsing, it will be because of invalid JSON
how should i call in html if i want to call country in address array please help me <li *ngFor="let address of addresses">FirstName:{{ persons.addresses.City }}</li></ul> is it right
|
1

In your person-list.service.ts file convert the response into JSON.

Map the response to JSON.

return this.http.get('app/person/person.json')
    .map(response => response.json())
    // .do(data => console.log('server data:', data))
    .catch(this.handleError);

Or else you can convert the response from component itself.

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.