angularhttprequesthttp-parameters

issue in query params in angular 8


I have a problem with the query parameters in angular 8. This is the code:

headers = {
        headers: new HttpHeaders({
            'Content-Type' : 'application/json',
            'Accept': 'application/json'
        })
    };

login(username, password) {

        console.log('login');

        let params = new HttpParams();
        params = params.append('username', username);
        params = params.append('password', password);
        let options = { headers: this.headers, params: params };

        return this.http.post<any>(this.host + 'login', options).pipe(map(data => {

                console.table(data);
                this.setSession(data);
                this.currentUserSubject.next(data.user);

            }));

    }

I also tried

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

and

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

and

let params = new HttpParams().append('username', username).append('password', password);

The backend server get username and password as undefined, previously I had this code that worked correctly:

 login(username, password) {

    console.log('login');

    return this.http.post<any>('http://localhost:8080/login?username='+username+'&password='+password, 
        {headers:{
            'Content-Type' : 'application/json',
            'Accept': 'application/json'}} 
    ).pipe(map(data => {

        this.setSession(data);
        this.currentUserSubject.next(data.user);

    }));

}

What's wrong? Thanks


Solution

  • I'd write it like this

    const options = {headers: this.headers, params: {username, password}};
    this.http.post<any>(this.host + 'login', null, options);
    

    You need to change your headers object, there's no need for the HttpHeader wrapper around it

    headers = {
        'Content-Type' : 'application/json',
        'Accept': 'application/json'
    };
    

    Btw: if your don't send a body maybe reevaluate the need for a post request