【问题标题】:How to correctly handle/ get correct JSON response with PHP API and AngularJS 2 services?如何使用 PHP API 和 AngularJS 2 服务正确处理/获取正确的 JSON 响应?
【发布时间】:2017-09-30 01:49:19
【问题描述】:

这是我的后端 MySQL 的问题。一个查询给了我这组数据

{"candidat":[{"ID":1,"nom":"Danny","prenom":"Hariot","parti":"Quamba","departement":"Ukraine","commune":"Chapayeve"},{"ID":2,"nom":"Shari","prenom":"Adamkiewicz","parti":"Babbleopia","departement":"Sweden","commune":"Täby"}]

数组数组,我想访问我的 Angular 项目的嵌套数组。我是说这部分

[{"ID":1,"nom":"Danny","prenom":"Hariot","parti":"Quamba","departement":"Ukraine","commune":"Chapayeve"},{"ID":2,"nom":"Shari","prenom":"Adamkiewicz","parti":"Babbleopia","departement":"Sweden","commune":"Täby"}]

这是我的组件

import { IPaeComponent } from './paeI';
import { NgModel } from '@angular/forms/src/directives';
import { Component, OnInit } from '@angular/core';
import { CandidatService } from './paeServices';

@Component({
    selector : 'pae-app',
    moduleId : module.id,  
    templateUrl : 'pae1.html'
})

export class PaeComponent implements IPaeComponent{
    prog1 : string ="Programme d'Appui aux Elections";
    progName1 : string ="Enquête sur les candidats";
    searchbar : string ='';
    progEl1 : string ="Listes des candidats ciblés";
    candInfo : any [];
    filter : string;

    candidats : IPaeComponent;
    errorMessage : string;

    constructor (private _candidatService : CandidatService){

    }

    ngOnInit(): void {
      this._candidatService.getCandidatInfo()
            .subscribe(candidats => this.candInfo = candidats,
            error => this.errorMessage = <any>error);
    }

}

我的服务:

import { IPaeComponent } from './paeI';
import { Injectable } from '@angular/core';
import { Http, Response , Headers, RequestOptions} from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map'
import 'rxjs/add/operator/do'
import 'rxjs/add/operator/catch'

@Injectable()
export class CandidatService {
    private _candidatUrl ='http://localhost/CRUD/api.php/candidat?transform=1';

    constructor(private _http : Http){

    }

 ///////////////////////////////////////////////////////
 //////////////////////////////////////////////////////
 //////////////////////CRUD///////////////////////////
 ////////////////////////////////////////////////////
 ///////////////////////////////////////////////////   





    getCandidatInfo() : Observable<IPaeComponent[]>{
        return this._http.get(this._candidatUrl)
        .map((response : Response)=><IPaeComponent[]> response.json())
        .do(data => console.log('All '+ JSON.stringify(data)))
        .catch(this.handleError);
    }

    private handleError(error : Response){
            console.error(error);
            return Observable.throw(error.json().error || 'Server Error');
    }

      addCandidatInfo (body: Object): Observable<IPaeComponent[]> {
        let bodyString = JSON.stringify(body); // Stringify payload
        let headers      = new Headers({ 'Content-Type': 'application/json' }); // ... Set content type to JSON
        let options       = new RequestOptions({ headers: headers }); // Create a request option

        return this._http.post(this._candidatUrl, body, options) // ...using post request
                         .map((res:Response) => res.json()) // ...and calling .json() on the response to return data
                         .catch((error:any) => Observable.throw(error.json().error || 'Server error')); //...errors if any
    }   


    updateCandidatInfo (body: Object): Observable<IPaeComponent[]> {
        let bodyString = JSON.stringify(body); // Stringify payload
        let headers      = new Headers({ 'Content-Type': 'application/json' }); // ... Set content type to JSON
        let options       = new RequestOptions({ headers: headers }); // Create a request option

        return this._http.put(`${this._candidatUrl}/${body['id']}`, body, options) // ...using put request
                         .map((res:Response) => res.json()) // ...and calling .json() on the response to return data
                         .catch((error:any) => Observable.throw(error.json().error || 'Server error')); //...errors if any
    }   


    removeInfo (id:string): Observable<IPaeComponent[]> {
        return this._http.delete(`${this._candidatUrl}/${id}`) // ...using put request
                         .map((res:Response) => res.json()) // ...and calling .json() on the response to return data
                         .catch((error:any) => Observable.throw(error.json().error || 'Server error')); //...errors if any
    }   
}

当我在浏览器中调试时,它的样子:

提前感谢您的帮助

【问题讨论】:

    标签: php mysql api angular typescript


    【解决方案1】:

    只需从您的响应中提取数组:

    getCandidatInfo() : Observable<IPaeComponent[]>{
        return this._http.get(this._candidatUrl)
        .map((response : Response)=><IPaeComponent[]> response.json().candidat) // here
        .do(data => console.log('All '+ JSON.stringify(data)))
        .catch(this.handleError);
    

    【讨论】:

    • 太棒了!很高兴听您这么说! :)
    【解决方案2】:

    试试这个

    this._candidatService.getCandidatInfo()
            .subscribe(candidats => {
              this.candInfo = candidats.candidat;
              // if you want get value from particular index
              cosnole.log(this.candInfo[0]);
    
              // Or you can iterate loop to get each value
            },
            error => this.errorMessage = <any>error);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-01
      • 2018-09-14
      • 1970-01-01
      • 1970-01-01
      • 2015-03-19
      • 2015-02-27
      • 2020-03-07
      相关资源
      最近更新 更多