【问题标题】:How will i pass query parameters to REST API inside a service in an angular application?我如何将查询参数传递给 Angular 应用程序中的服务内的 REST API?
【发布时间】:2019-09-19 21:28:01
【问题描述】:

我正在尝试将服务内的查询参数传递给 REST API。

我应该如何传递给 API 的示例。(预期)

http://localhost:2000/world/123456789/avengers?type=fruits&fields=_all

试过如下:

     all(countId) {
        const headers: HttpHeaders = new HttpHeaders({
            "_id" : countId, 
            "content-type" : "application/json"
        });
        let params = new HttpParams();
        params = params.append("type", "fruits");
        params = params.append("fields", "_all");
        const options = {
            headers: headers,
            params: params
        };
        return this.http.put ( "http://localhost:2000/world/123456789/avengers", options )
    }

但我无法传递它们有查询参数。我将如何做到这一点?

【问题讨论】:

    标签: angular typescript api service query-parameters


    【解决方案1】:

    您当前正在将您的选项作为请求有效负载发送,就像您发现的那样。如果没有payload,可以通过null

    all(countId) {
      // ....
      return this.http.put("...", null, options)
                                  ^^^^
    }
    

    【讨论】:

      【解决方案2】:

      因为 HTTP PUT/POST 发送正文而不在 URL 中附加查询字符串(您可以使用一些库来构建查询字符串),因此您需要构建您的 URL 和选项

       * @param url The endpoint URL.
           * @param body The resources to add/update.
           * @param options HTTP options
           *
           * @return An `Observable` of the response, with the response body as a JSON object.
           */
          put(url: string, body: any | null, options?: {}
      
      
      all(countId) {
              const headers: HttpHeaders = new HttpHeaders({
                  "_id" : countId, 
                  "content-type" : "application/json"
              });
      
              const options = {
                  headers: headers,
                  params: params
              };
              return this.http.put ( "http://localhost:2000/world/123456789/avengers??type=fruits&fields=_all", options)
          }
      

      【讨论】:

      • localhost:2000/world/123456789/… 将像这样传递而不是作为查询参数传递......你的意思是我应该添加'?'我一个人
      • 是的!!!..它们作为查询参数获取。但是,在查询参数和请求有效负载中:|
      • 如果我再次从选项中删除参数相同的行为!!
      • 我发现PUT不能在查询字符串中追加正文,需要手动追加
      【解决方案3】:

      您可以将它们作为参数发送

      const headers: HttpHeaders = new HttpHeaders({
                  "_id" : countId, 
                  "content-type" : "application/json"
              });
      let params = new HttpParams().set('type',fruits).set('fields',_all);
      return this.http.put ( "http://localhost:2000/world/123456789/avengers",{ params: params, headers: headers})
      

      或者你可以发送选项

      let options: HttpOptions;
      options.headers = headers;
      options.params = params;
      return this.http.put ( "http://localhost:2000/world/123456789/avengers", options )
      

      【讨论】:

      • 我尝试了这两种方法....参数被传递到“请求有效负载”而不是“查询参数”:(
      • 我已经更新了他的答案,请检查 plz 并添加屏幕截图以请求能够获得更多详细信息
      • 我已经尝试过您的方法,并且我已经编辑了问题...添加了屏幕截图如何在请求有效负载中传递参数。而是在标题和查询参数中传递参数
      【解决方案4】:

      /********** 这是我的组件文件 ***********/

      page: any;
      error: {};
      orderObj: {};
      
      ngOnInit(){
        const type: string = this.route.snapshot.queryParamMap.get('type');
        const fields: string = this.route.snapshot.queryParamMap.get('fields');
        this.orderObj = {'type' : type, 'fields' : fields}
      
        this.route.paramMap.pipe(
        switchMap((params: ParamMap) =>
          this.cmspageService.getPage(params.get('slug'), this.orderObj)
        )
        ).subscribe(
        (data: any) => this.page = data,
        error => this.error = error
        );
      }
      

      /********** 这是我的服务文件 ***********/

      public queryStringUrl : string
      
      getPage(slug: string, data:object){
         if(data){
            this.queryStringUrl = '?';
            let i = 0; 
            for (var p in data) {
             if (data.hasOwnProperty(p)){
              if(i != 0)
              this.queryStringUrl += '&';
              this.queryStringUrl +=  p + '=' + data[p];
            }
            i++;
          }
          //return this.queryStringUrl;
          // alert(this.queryStringUrl);
      }
      
      return this.http.get<Page>('http://localhost/dev/blogger/api/page/' + slug + this.queryStringUrl,)
      .pipe(
        catchError(this.handleError)
      );
      }
      

      参考链接:https://alligator.io/angular/query-parameters/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-09-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多