问题描述
因为我已经升级到Angular 5并开始使用httpclient.我无法获得一个简单的登录功能即可工作.有人可以帮我吗?
身份验证服务:
登录名(电子邮件:字符串,密码:字符串):Observable< boolean>{返回this.http.post(environment.api_url +'/authenticate',{电子邮件:电子邮件,密码:密码}).map(response => {if(response&&response.token){localStorage.setItem('token',response.token);返回true;} 别的 {返回false;}}).catch(err => Observable.of(false));}
和登录页面控制器:
login(){this.loading = true;this.auth.login(this.credentials.email,this.credentials.password).订阅(数据=>{如果(数据){this.router.navigate([this.returnUrl]);}},数据=>{this.loading = false;如果(data.error&&data.error.message){this.loginError = data.error.message;}});}
这给了我错误:
对于 http
,响应主体的类型为 any
,这意味着您可以使用任何属性无需TypeScript抱怨.这通过 HttpClient
进行了更改,默认情况下,它仅是标准的 Object
,它将TypeScript视为基本对象而没有 token
属性./p>
您在这里至少有3个基本选项:
- 从
response.token
更改为response ['token']
. - 使用
this.http.post< any>
并继续访问response.token
. -
创建例如一个新的界面,如下所示:
接口AuthenticateResponse {令牌:字符串}
有了这个,您就可以使用
this.http.post< AuthenticateResponse>
并拥有TypeScript提供的类型安全性.
您可以在文档的对响应进行类型检查中了解有关此内容的更多信息.
since i've upgraded to Angular 5 and started using httpclient. I am unable to get just a simple login function to work. Can someone help me out?
auth service:
login(email: string, password: string): Observable<boolean> {
return this.http.post(environment.api_url + '/authenticate', {email: email, password: password})
.map(response => {
if (response && response.token) {
localStorage.setItem('token', response.token);
return true;
} else {
return false;
}
}
)
.catch(err => Observable.of(false));
}
and the login page controller:
login() {
this.loading = true;
this.auth.login(this.credentials.email, this.credentials.password)
.subscribe(
data => {
if (data) {
this.router.navigate([this.returnUrl]);
}
},
data => {
this.loading = false;
if (data.error && data.error.message) {
this.loginError = data.error.message;
}
});
}
This gives me error(s):
With http
, the response body was typed as any
, which meant you could use whatever properties you needed without TypeScript complaining. This changed with HttpClient
, whereby it defaults to just a standard Object
, which upsets TypeScript as a basic object does not have a token
property.
You have at least 3 basic options here:
- Change from
response.token
toresponse['token']
. - Use
this.http.post<any>
and continue to accessresponse.token
. Create e.g. a new interface, such as the following:
interface AuthenticateResponse { token: string }
With this, you can then use
this.http.post<AuthenticateResponse>
and have the type-safety offered by TypeScript.
You can read more about this in Typechecking the response from the docs.
这篇关于HTTPClient服务中的角度登录功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!