【问题标题】:Error : Http failure during parsing in Angular错误:在 Angular 中解析期间的 Http 失败
【发布时间】:2018-06-02 19:54:15
【问题描述】:

我正在学习 Angular,我想在 HTML 页面上显示 JSON 数据。错误是在 Angular 中解析期间的 Http 失败。我不知道为什么请告诉我我的错误并给我链接如何显示多种类型的 JSON 数据

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);
  }
 }

【问题讨论】:

    标签: angular


    【解决方案1】:

    这在技术上是无效的 JSON,因为“Mumbai”之后的尾随逗号

    应该是

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

    编辑

    更新之后,也是无效的,因为它需要被包裹在一个对象中,像这样:

    {
        "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
    
        }]
    
    }
    

    这将创建一个对象,其中包含 2 个数组:“Addresses”和“ContactNumbers”

    【讨论】:

    • @VinitMapari JSON 中一定有其他错误。您能否编辑您的问题以包含完整的 JSON 文件?
    • @VinitMapari 我刚刚根据您更新的 JSON 更新了答案
    • 我已更新并检查,请告诉我错误我认为调用 html 页面时出错告诉我您的意见
    • @VinitMapari 是的,我更新了我的答案,请看一下。任何时候提到解析错误,都是因为无效的JSON
    • 如果我想在地址数组中调用国家,我应该如何在 html 中调用,请帮助我
    • FirstName:{{ persons.addresses.City }}对吗
    【解决方案2】:

    在您的 person-list.service.ts 文件中将响应转换为 JSON。

    将响应映射到 JSON。

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

    否则您可以转换来自组件本身的响应。

    【讨论】:

      猜你喜欢
      相关资源
      最近更新 更多
      热门标签