在Angular 6应用程序中发布请求

时间:2019-03-06 19:55:23

标签: angular rest http-post

在我的Angular应用程序中,我正在使用我创建的服务中的get请求从api获取数据,我也试图向该api创建一个post请求,我的代码似乎无法正常工作。到目前为止,我的代码是:

    import { Injectable } from '@angular/core';
    import { HttpClient, HttpEventType, HttpHeaders, HttpRequest, HttpResponse, HttpErrorResponse } from '@angular/common/http';
    import { HttpClientModule } from '@angular/common/http';
    import { Observable, of, throwError } from 'rxjs';
    import { catchError, retry } from 'rxjs/operators';


    @Injectable({
      providedIn: 'root'
    })
    export class 

nowService {

  serviceApiUrl: string = 'api/incident';


  constructor(
    private http: HttpClient,

  ) { }

  getAll(): Observable<any> {
    return this.http.get<any>(this.serviceApiUrl)
      .pipe(
        catchError(this.handleError)
      );
  }

  getIncidents(customerId): Observable<any> { 
    return this.http.get<any>(this.serviceApiUrl + "?customer_id=" + customerId )
      .pipe(
      catchError(this.handleError)
    );
  }

  postIncidents(customerId): Observable<any> { 
    return this.http.post<any>(this.serviceApiUrl + "?customer_id=" + customerId )
      .pipe(
      catchError(this.handleError)
    );
  }


  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      console.log(error.error.message)

    } else {
      console.log(error.status)
    }
    return throwError(
      console.log('Something has happened; Api is not working!'));
  };

}

它将customer_id作为参数。我收到的错误是:

预期2-3个参数,但得到1个。

5 个答案:

答案 0 :(得分:4)

POST请求用于将某些内容插入数据库时​​使用。 HttpClient post函数至少需要2个参数。第一个是URL,第二个是请求正文(您要插入数据库的对象)。

例如,如果要创建用户,这是标准方式

this.httpClient.post<any>('/api/user', {username: 'test', password: '123'});

这将返回响应主体的Observable(可能与您作为具有id的第二个参数传递的对象相同)。如果您希望该函数返回整个响应(包括状态和其他有用数据),则可以向其传递第三个参数(选项)

this.httpClient.post<any>('/api/user', {...}, {observe: 'response'});

这将返回Observable,它在完成时将发出类似以下内容的信息:

{
  body: {
    id: 1,
    username: 'test',
    password: '123'
  },
  status: 201 // Indicates the creation was successful (sometimes 200),
  headers: {...} // you can pass them as property of 3rd argument
}

由于您的端点不希望请求包含正文,因此您可以这样做:

postIncidents(customerId): Observable<any> { 
  return this.http.post<any>(this.serviceApiUrl+"?customer_id="+customerId, null)
    .pipe(catchError(this.handleError));
  }

将数据发送到服务器:https://angular.io/guide/http#sending-data-to-the-server

有关http状态代码的更多信息:https://developer.mozilla.org/en-US/docs/Web/HTTP/Status

答案 1 :(得分:0)

您缺少尸体,请尝试添加一个空对象

return this.http.post<any>(this.serviceApiUrl + "?customer_id=" + customerId, {})
      .pipe(
      catchError(this.handleError)
    );

答案 2 :(得分:0)

问题来自POST方法:

  return this.http.post<any>(url, body, headers)

但是,根据您使用的Angular版本,可能有所不同。

Angular Docs

答案 3 :(得分:0)

按照惯例,Http POST请求应包含在请求正文中的数据。本质上,您是在告诉服务器创建资源。为此,您将资源(在您的情况下为incident)放入POST请求的请求正文中。

要按角度进行此操作,请将其作为第二个参数传递。

postIncidents(customerId, incident): Observable<any> { 
  const url = this.serviceApiUrl + "?customer_id=" + customerId;
  return this.http.post<any>(url, incident)
    .pipe(
    catchError(this.handleError)
  );
}

作为一般惯例,我尝试在发布请求时保持URL尽可能干净,并在获取数据时保存查询字符串参数。最干净的是确保customerIdincident数据中包含的属性。然后可以将其清除为:

postIncidents(incident): Observable<any> { 
  return this.http.post<any>(this.serviceApiUrl, incident)
    .pipe(
    catchError(this.handleError)
  );
}

答案 4 :(得分:0)

//示例1:

import { HttpClient } from '@angular/common/http';


constructor(private http: HttpClient) {}

serviceurl:any = http://localhost:3000/;

postIncidents (customerId): Observable<any> {

  const Url = `${serviceurl}`;

  const body = `customer_id= ${customerId}`;

    return this.http.post<any>( Url , body, {})

    .pipe(map(res => res))

    .catch(err => err);
 }

示例2:

//使用http标头发送数据,内容类型为json

 import { HttpHeaders } from '@angular/common/http';

 const httpOptions = {

 headers: new HttpHeaders({

   'Content-Type':  'application/json'

 })};

 postIncidents (customerId): Observable<any> {

   const Url = `${serviceurl}`;

   const body = JSON.stringify(

   {

    customer_id: customerId 

   });

   return this.http.post<any>(Url, body, httpOptions)

   .pipe(map(res => res))

   .catch(err => err);
 }