0

I am calling an API using Get method, I want to just get the 'Query string parameters' which has been appended from backend. For example https://api.npms.io/v2/search?q=scope:angular&lang='fr''. From this API lang='fr' has been appended from backend. I need to get the last 'query parameters' lang='fr'.

app.component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
    
@Component({ selector: 'app', templateUrl: 'app.component.html' })
export class AppComponent implements OnInit {
    totalAngularPackages;
    
    constructor(private http: HttpClient) { }
    
    ngOnInit() {      
        // Simple GET request with response type <any>
        this.http.get<any>('https://api.npms.io/v2/search?q=scope:angular&lang='fr'').subscribe(data => {
            this.totalAngularPackages = data.total;
        })
    }
}
insertusernamehere
  • 23,204
  • 9
  • 87
  • 126
  • "https://api.npms.io/v2/search?q=scope:angular&lang='fr'" from this url last parameter – fullstackdeveloper Aug 10 '21 at 08:09
  • Does this answer your question? [How can I get query string values in JavaScript?](https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) – Inigo Jun 08 '23 at 14:39

1 Answers1

0

You can simply extract the search parameter from the URL by:

  • creating an URL object from the string
  • extracting the search parameters
  • finally get the parameter you want

const url = new URL("https://api.npms.io/v2/search?q=scope:angular&lang='fr'");
const params = new URLSearchParams(url.search);

console.log(params.get('q'));
console.log(params.get('lang'));

See also:


Keep in mind that 'https://api.npms.io/v2/search?q=scope:angular&lang='fr'' is an invalid string. Either escape the single quotes or use double quotes:

const url = 'https://api.npms.io/v2/search?q=scope:angular&lang=\'fr\'';
const url = "https://api.npms.io/v2/search?q=scope:angular&lang='fr'";
insertusernamehere
  • 23,204
  • 9
  • 87
  • 126
  • Thanks for your answer, but how to get this full URL in angular https://api.npms.io/v2/search?q=scope:angular&lang='fr' , Since 'https://api.npms.io/v2/search?q=scope:angular ' coming from API, passing different request but the last request &lang='fr' appending from backend – fullstackdeveloper Aug 10 '21 at 09:45
  • I'm sorry, but I don't understand, what you mean. You're receiving the URL from another API call? You have to add that code to the question a s well. Where exactly is the `lang` parameter added? Maybe you have to explain your problem more detailed. – insertusernamehere Aug 10 '21 at 09:48
  • I am doing the API call with the same URL https://api.npms.io/v2/search?q=scope:angular&lang='fr' by passing the first request q=scope:angular but the last request is getting appended by backend team &lang='fr' , so I need to get the last request lang='fr' which is appended by backend – fullstackdeveloper Aug 10 '21 at 09:55