Login My onSubmit(): onSubmit() { this.personServi" /> Login My onSubmit(): onSubmit() { this.personServi" /> Login My onSubmit(): onSubmit() { this.personServi"/>

HttpParams dont request filtered JSON

326 Views Asked by At

I have a really simple http request.

My Front end:

<button mat-button (click)="onSubmit()">Login</button>

My onSubmit():

onSubmit() {

this.personService.getPersonByName().subscribe(person => {
  console.log('Person', person);
});

My PersonService getPersonByName():

  private personURL = 'http://localhost:3000/api/persons'

  constructor(private http: HttpClient) { }


  getPersonByName(): Observable<Person> {

     let params = new HttpParams().set('username', 'SwaX');

     return this.http.get<Person>(this.personURL, { params });
 }

What i get:

enter image description here

Why do i get 3 Objects instead of 1?

3

There are 3 best solutions below

3
Stephen Whitmore On

This is a problem with your API, not Angular. You're not filtering down your response before sending it back over the wire. You could fix it on the API side and have it return a single object instead of an array of objects or you could filter the object out of the response in your service's getPersonByName() method using map -

getPersonByName(username: string): Observable<Person> {
    return this.http.get<Person[]>(this.personURL)
        .pipe(
           .map(people => people.find(person => person.username === username)
        );
}
6
Adrita Sharma On

Try:

return this.http.get<Person>(`${this.personURL}?username=SwaX`);

or,

return this.http.get<Person>(`${this.personURL}/1`);

based on your backend param

0
Selast Lambou On

Maybe you're missing something small, and it's that the HttpParams in the request would be mapped to join the URL. Then doing

getPersonByName(): Observable<Person> {
   let params = new HttpParams().set('username', 'SwaX');
   return this.http.get<Person>(this.personURL, { params });
}

is similar to doing

getPersonByName(): Observable<Person> {
   return this.http.get<Person>(this.personURL + '?username=Swax');
}

Which should produce the same results. As it's a GETrequest, so you can also test it using your browser. Simply open

http://localhost:3000/api/persons?username=Swax

in your browser and see what comes. This way you'll be able to determine if the problem comes from your API or not.