'Angular 14: Calling GET or POST always return null response
I have AuthService which has login() method like:
private authUrl = "http://localhost:8080/myapi/auth";
login(username: string, password: string) {
let options = {
headers: new HttpHeaders()
.set('Content-Type', 'application/json')
.append('Authorization', 'Basic ' + btoa(username + ":" + password))
};
return this.http.get(`${this.authUrl}`, options);
}
I have component making a call to this service like:
login() {
this.authService.login(uid, pwd).subscribe(resp => {
console.log("received resp : " + resp ); //ALWAYS NULL ???
},
error => {
console.log("got error: " + error);
},
() => {
console.log("successfully completed call");
}
);
}
The login()
method shows its response in browser dev tools Network tab as 200 OK. I also see my custom headers being returned.
So, there is no errors as expected. However, the returned resp
is always null, so the output on the console is always
received resp: null
successfully completed call
Why is resp
returned in response always null?
Solution 1:[1]
You can have some authentication service with:
login(uname: string, pass: string) {
return this.http.post<any>(`${this.authUrl}`, {"uname": uname, "pass": pass},
{
headers: new HttpHeaders()
.set('Content-Type', 'application/json')
, observe: 'response'
})
.pipe(tap(res => {
if (res.ok) {
// you are authenticated
}
}))
}
, then call it from your controller:
login() {
this.authorizationService.login(this.loginForm.value.uname, this.loginForm.value.pass)
.subscribe(res => {
if (res.ok) {
// you are authenticated
}
},
error => {
// you got error
},
() => {
// you completed call successfully, then this callback is called
});
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | pixel |