Get ID from API



我有一个这样的API网址:localhost:3000/api/categories?id=1。 如何通过查询参数获取值中的 id 并在 Angular 5 中删除此对象。我的代码是这样的角度:

private url = 'http://localhost:3000/api/categories';
deleteMovie(categoryId: number): Observable<CategoriesModel> {    
const url = url to get value
return this.http.delete<CategoriesModel>(url, httpOptions).pipe(
tap(_ => console.log(`Deleted category with id = ${categoryId}`)),
catchError(error => of(null))
);
}

从 MDN 从字符串 URL 获取 ID:

var paramsStringURL = new URL("http://localhost:3000/api/categories?id=1");
var searchParams = new URLSearchParams(paramsStringURL.search);
console.log(searchParams.get("id"));

对于从实际 URL 获取的角度方式:角度 2 检查 url 中是否存在查询参数

您需要导入"激活路由":

import {ActivatedRoute } from "@angular/router";

然后像这样订阅查询参数:

constructor( private route: ActivatedRoute) {}
ngOnInit() {
this.route.queryParams.subscribe(params => {
let url = params['id'];
});
}

您需要将categoryId添加为HttpParams,您可以这样做。我看到您正在为选项使用变量,因此请添加HttpParams,例如:

private url = 'http://localhost:3000/api/categories';
deleteMovie(categoryId: number): Observable<CategoriesModel> {   
// create params, create a string from the number, since params accepts only string
const params = new HttpParams().set('id', categoryId.toString());
const httpOptions = {
headers: new HttpHeaders({
// ...
}),
params: params // add this
}
return this.http.delete<CategoriesModel>(url, httpOptions).pipe(
tap(_ => console.log(`Deleted category with id = ${categoryId}`)),
catchError(error => of(null))
);
}

使用HttpParams您将获得所需的网址:localhost:3000/api/categories?id=1

相关内容

  • 没有找到相关文章