首页 > 解决方案 > 如何使用 HttpRepsonse 从 post 方法获得回报

问题描述

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

我发现这可能是因为我的 http.post 没有 Httpresponse 所以角度无法获取标题信息。

服务.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'))
  );

}

组件.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,我想用它来做不同的通知。

标签: angularhttpresponse

解决方案


请首先使用 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;
      }));

推荐阅读