我是 angualr 2 的新手。我正在做一个小的练习应用程序。我有一个用户登录时的身份验证服务。这是它的登录功能。
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)
);
}
当我在组件 angualr 中调用此函数时,出现错误“属性订阅在类型‘订阅’上不存在。
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']);
}
}
)
}
我想为什么 angular 会给出这个错误,因为我在登录函数中使用订阅以及在调用登录函数时。请提出一些解决方案或替代方法来实现我试图在登录功能中实现的结果。
最佳答案
你自己对问题的分析是正确的!删除服务中的 .subscribe
并仅在使用它的组件中使用它。您的服务应该在 .map
运算符之后返回。
如果您订阅该服务,它将返回一个 Subscription
而不是 Observable
,这确实是您收到错误的原因。
关于angular - 订阅不存在类型 'Subscription',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44686959/