如何使用HttpRepsonse从post方法获得回报

时间:2018-12-23 09:24:20

标签: angular httpresponse

我无法从返回消息中获取headers.get(status)的结果。

我发现可能是因为我的http.post没有Httpresponse,所以angular无法获取标头信息。

service.ts:

onCreateData(service: LoginFormService) {

const request = JSON.stringify(
  { dataYear: service.form.get('dataYear').value,
    dataMonth: service.form.get('dataMonth').value,
    population: service.form.get('population').value,
    sources: service.form.get('sources').value
  }
);

return this.http.post(this.createDataUrl, request, httpOptions)
  .pipe(
    catchError(this.handleError('onCreateData'))
  );

}

component.ts:

onSubmit() {
this.service.onCreateData(this.service).subscribe(

  (res: Response) => {
    console.log('-----');
    console.log(res.headers.get(status));
    this.service.form.reset();
    this.service.initializeFormGroup();
    this.notificationService.success(':: Submitted successfully');
    this.dialogRef.close();
  }
);

}

如果我可以获取headers.status,我想用它来进行其他通知。

1 个答案:

答案 0 :(得分:0)

请先使用HttpClient而不是http,因为不推荐使用http。

从'@ angular / common / http'导入{HttpClient,HttpRequest};

示例:1

 const req = new HttpRequest('POST','YOUR_URL',POST_DATA,{reportProgress: true});
return this.http.request(req);

示例:2

this.http.post<Type of response you will get>('YOUR_URL',{
          observe: 'body',
          responseType: 'json'
        })
    }),map(
      ( response)=>{
       ///******************Do some Changes or check in Response************///
        return  response;
      }));

示例:3

this.http.post('YOUR_URL',{
          observe: 'body',
          responseType: 'json'
        })
    }),map(
      ( response)=>{
       ///******************Do some Changes or check in Response************///
        return  response;
      }));