Я пытаюсь передать параметры запроса внутри службы в 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 )
}
Но я не могу передать им параметры запроса. Как я это сделаю?
4 ответа
В настоящее время вы отправляете свои опции в качестве полезной нагрузки запроса, как вы обнаружили. Если у вас нет полезной нагрузки, вы можете передать null
:
all(countId) {
// ....
return this.http.put("...", null, options)
^^^^
}
Вы можете отправить их как параметры
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 )
/ ********** Это мой компонентный файл *********** /
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/
Поскольку 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)
}
Похожие вопросы
Связанные вопросы
Новые вопросы
angular
Вопросы по Angular (не путать с AngularJS), веб-фреймворку от Google. Используйте этот тег для угловых вопросов, которые не относятся к конкретной версии. Для более старой веб-платформы AngularJS (1.x) используйте тег angularjs.