处理http post数组,显示undefined

时间:2018-02-02 09:27:23

标签: arrays json angular typescript post

我有一个大问题。我想显示这个json,但返回未定义的值。

{"StatusCode":0,"StatusMessage":"OK","StatusDescription":{ "datas": [
{"sensor_serial":"SensorSerial1", "id":"11E807676E3F30B5"},
{"sensor_serial":"sensorserial2", "id":"11E807679D82841L"},
{"sensor_serial":"sensorserial3", "id":"11E80767A5CD2820"} ]
,"home_id":"11E80768K", "active":0, "homebox_id":"11E8076792BD0164J",
"date_created":"2018-02-01T15:55:54.000Z", "date_modified":null,
"serial_number":"serialn1", "user_id":"3"} }

我在service.ts中使用此代码

public getHomeboxPById(id: string): Observable<HomeboxP> {
    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    let urlSearchParams = new URLSearchParams();
    urlSearchParams.append('home_id', id);
    urlSearchParams.append('token', this.auth.getCurrentUser().token);
    let body = urlSearchParams.toString();
    return this.http.post(Api.getUrl(Api.URLS.getHomeboxPById), body, {
    headers: headers
    })
    .map((response: Response) => {
        let res = response.json();
        if (res.StatusCode === 0) {
         return new HomeboxP(res.StatusDescription[0]);
        } else if (res.StatusCode === 1) {
         this.auth.logout();
        } else {
           return new HomeboxP(null);
        }
    });
}

在ts代码中,我将此方法称为getHomeboxPById,就像这样

editHomeboxPForm: FormGroup;
homeboxp: HomeboxP;
    this.editHomeboxPForm = this.fb.group({
      'homebox_id': new FormControl('', Validators.required)
    });
}

populateFormHomeboxP() {
    this.activatedRoute.params.subscribe(
    params => {
    this.ws.getHomeboxPById(params['id']).subscribe(
     homeboxp => {
        console.log(homeboxp);  // display undefined
        this.homeboxp = homeboxp;
        this.editHomeboxPForm.controls['homebox_id'].setValue(homeboxp.homebox_id);
        }
      );
     }
   );   
}

拜托,能帮助我,为什么不工作?

1 个答案:

答案 0 :(得分:1)

{"StatusCode":0,"StatusMessage":"OK","StatusDescription":{ "datas": [
{"sensor_serial":"SensorSerial1", "id":"11E807676E3F30B5"},
{"sensor_serial":"sensorserial2", "id":"11E807679D82841L"},
{"sensor_serial":"sensorserial3", "id":"11E80767A5CD2820"} ]
,"home_id":"11E80768K", "active":0, "homebox_id":"11E8076792BD0164J",
"date_created":"2018-02-01T15:55:54.000Z", "date_modified":null,
"serial_number":"serialn1", "user_id":"3"} }

如果这是

的回应
this.http.post(Api.getUrl(Api.URLS.getHomeboxPById)

然后问题是res.StatusDescription[0],它应该是res.StatusDescription,如:

new HomeboxP(res.StatusDescription);