I am new to angualr 2. And I am making a small application for practice. I have a service for authentication of users when they log in. And here is it's login function.
login(email:string, password:string){
var loginrul="https://filing.herokuapp.com/api/v1/auth/login/";
return this.http.post(loginrul,JSON.stringify({ password: password,email: email }),
{headers:new Headers({'Content-Type':'application/json'})}
).map(res=>res.json()).
subscribe(
data => localStorage.setItem('id_token',data.auth_token),
error=>console.log(error)
);
}
When I call this function in component angualr gives error that "Property subscribe does not exist on type 'Subscription'.
doLogin(event) {
console.log(event);
console.log(this.loginForm.value);
let formData = this.loginForm.value;
let email = this.loginForm.controls.email.value;
let password= this.loginForm.controls.password.value;
this.auth.login(email,password).subscribe(res =>{
console.log(res);
if(res.status===200){
this.router.navigate(['dashboard']);
}
}
)
}
I think why angular is giving this error because i am using subscribe in login function as well as while calling login function. Please suggest some solution or an alternative approach to achieve the result which I am trying to achieve in login function.
Your own analysis of the problem is correct! Remove the .subscribe
in your service and only use it in your component where you consume it. Your service should return after the .map
operator.
If you subscribe in the service, it will return an Subscription
instead of an Observable
, and that's indeed why you are getting your error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With