Reputation: 4972
I created this auth-api.ts service, having a login method:
login(username, password)
{
let headerOptions = new HttpHeaders();
headerOptions.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
const httpParams = new HttpParams()
.set('username', username)
.set('password', password);
return this.http.post('http://dev.local/scripts/login.php', httpParams, {
headers: headerOptions
}).pipe(map(
res=>{
console.log('user '+res)
},
err=>
console.log(err)
))
}
On button click, this method will be called inside login.component.ts using this method:
login(){
const user = this.loginGroup.get('username').value;
const pass = this.loginGroup.get('password').value;
this.auth.login(user, pass).subscribe(
(data)=>{
console.log(data);
this.loginGroup.reset();
},
(error)=>{
console.log(error)
}
)
}
The problem is that the console.log(res)
from the api login method is returning the value, but the `console.log(data) from the second login method is returning undefined.
What I want is to make some conditions on data
, so that's why I can't.
Upvotes: 0
Views: 8317
Reputation: 4119
If you want to return and log the result in console use tap
operator instead of map
return this.http.post('http://dev.local/scripts/login.php', httpParams, {
headers: headerOptions
}).pipe(tap(
res=>{
console.log('user '+res)
},
err=>
console.log(err)
))
Upvotes: 4
Reputation: 162
Remove the pipe. You are mapping your response to console.log() which is why you are getting undefined in your component.
Also you can handle the error from the component.
login(username, password)
{
let headerOptions = new HttpHeaders();
headerOptions.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
const httpParams = new HttpParams()
.set('username', username)
.set('password', password);
return this.http.post('http://dev.local/scripts/login.php', httpParams, {
headers: headerOptions
});
}
In simple words, Pipe is used to transform your output. Here map operator maps your response to a method or some expression to get the required input. If suppose your response returns 2, then if I do,
map(response => response * 2)
,
your component will get data as 4 in subscribe method. I suggest you google for more information.
Upvotes: 2
Reputation: 78
**try this**
let headers = new Headers();
headers.set('Content-Type', 'application/x-www-form-urlencoded');
return this.http.post('http://dev.local/scripts/login.php',httpParams, { headers: this.headers }).toPromise();
Upvotes: 1