带有JSON参数的Typescript Rest API POST调用

问题描述:

我正在尝试找到一个代码示例,以JSON作为参数将POST请求发送到REST Api,并获取响应以及Typescript中的任何异常/错误代码.

I'm trying to find a code example to send a POST request to a REST Api with a JSON as parameter and get the response and any exceptions / error codes in Typescript.

您可以从类似的内容开始

You could start with something like that

服务

export class MyService{
  constructor(
    private httpClient: HttpClient) {
  }

   getSomethingFromServer():Observable<any>{
       return this.httpClient.get('you_request_url');
   }
}

组件

constructor(
    private myService: MyService) {
  }

  this.myService.getSomethingFromServer().subscribe(response => {
     // do whatever you want with the response
  }, error => {
     // handle error here
     // error.status to get the error code
  });