繁体   English   中英

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

[英]Post request in Angular 6 application

在我的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个。

当您想向数据库中插入内容时使用POST请求。 HttpClient post函数至少需要2个参数。 第一个是URL,第二个是请求正文(您要插入到DB中的对象)。

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

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

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

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

问题来自POST方法:

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

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

角度文档

按照约定,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)
  );
}

按照一般惯例,我会尽量在发布请求时保持网址的整洁,并在获取数据时保存查询字符串参数。 最干净的是确保customerIdincident数据中包含的属性。 然后可以将其清理为:

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

//示例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);
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM