Как передать параметры запроса в REST API внутри службы в угловом приложении? - PullRequest
1 голос
/ 01 мая 2019

Я пытаюсь передать параметры запроса внутри службы в 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 )
    }

Но я не могу передать их, имеет параметры запроса. Как мне это сделать?

enter image description here

Ответы [ 4 ]

1 голос
/ 01 мая 2019

Поскольку 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)
    }
1 голос
/ 01 мая 2019

В настоящее время вы отправляете свои опции в качестве полезной нагрузки запроса, как вы обнаружили.Если у вас нет полезной нагрузки, вы можете передать null:

all(countId) {
  // ....
  return this.http.put("...", null, options)
                              ^^^^
}
0 голосов
/ 02 мая 2019

/ ********** Это мой компонентный файл *********** /

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/

0 голосов
/ 01 мая 2019

вы можете отправить их как параметры

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 )
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...