0

I have an API url like this : localhost:3000/api/categories?id=1. How can i get id in value by query params and delete this Object in Angular 5. My code in angular like this :

    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))
    );
    }
AlexC
  • 95
  • 2
  • 7

3 Answers3

0

You need to import 'ActivatedRoute' :

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

and then subscribe to the queryParams like this:

constructor( private route: ActivatedRoute) {}

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

From MDN to obtain ID from string URL:

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

console.log(searchParams.get("id"));

For Angular way fetching from actual URL: Angular 2 Check if query parameter exists in the url

Shinjo
  • 677
  • 6
  • 22
0

You need to add the categoryId as HttpParams, you can do it like this. I see you are using a variable for the options, so add the HttpParams to that, like:

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

With the HttpParams you will get the desired url: localhost:3000/api/categories?id=1

AT82
  • 71,416
  • 24
  • 140
  • 167