【问题标题】:Post request in Angular 6 application在 Angular 6 应用程序中发布请求
【发布时间】:2019-03-06 19:55:23
【问题描述】:

在我的 Angular 应用程序中,我正在使用我创建的服务中的 get 请求从 api 获取数据,我也在尝试创建对该 api 的发布请求,我的代码似乎不起作用。到目前为止,我的代码是:

    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 个。

【问题讨论】:

    标签: angular rest http-post


    【解决方案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

    【讨论】:

      【解决方案2】:

      你缺少正文,尝试添加一个空对象

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

      【讨论】:

        【解决方案3】:

        问题来自POST方法:

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

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

        Angular Docs

        【讨论】:

          【解决方案4】:

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

          要在 Angular 中执行此操作,请将其作为第二个参数传递。

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

          作为一般做法,我会尝试通过发布请求使 URL 尽可能干净,并在获取数据时保存查询字符串参数。最干净的是确保 customerId 是包含在 incident 数据中的属性。然后它可以被清理成这样:

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

          【讨论】:

            【解决方案5】:

            // 示例一:

            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);
             }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2019-10-22
              • 2017-03-09
              • 2018-10-16
              • 1970-01-01
              • 1970-01-01
              • 2019-03-13
              • 2020-12-07
              • 1970-01-01
              相关资源
              最近更新 更多