我在使用带有第二个角度和打字稿的原生承诺时遇到了问题:
export class LoginComponent implements OnInit {
public user = {};
constructor( private authService:AuthenticationService) { }
ngOnInit() {
}
login() {
console.log( 'Connecting to server' );
this.authService.login( this.user ).then(( response ) => {
// works
console.log( response['success'] );
// error
console.log( response.success );
}, ( error ) => {
console.log( error );
});
}
}
下面是简单的服务,虚假连接到服务器:
export class AuthenticationService {
// ... some code ...
login( loginData ) {
let self = this;
return new Promise(function(resolve, reject){
// fake delay - for now is no back end
setTimeout(function() {
if ( loginData.username === 'username' && loginData.password === 'password' ) {
resolve({
message: "Successfully logged in",
success: true,
errors: null
});
} else {
reject({
message: "Wrong user data reperesented",
success: false,
errors: {
"username": true,
"password": true
}
});
}
}, 100);
});
}
// ... some code ...
}
试图搜索我必须做的事情来解决Property 'success' does not exist on type '{}'.
错误,但没有成功。
答案 0 :(得分:1)
这是因为上面的代码没有输入。
为了完成这项工作,它应该是
login( loginData ): Promise<any> { ... }
或
this.authService.login( this.user ).then(( response: any ) => { ... })
更好的方法是让类型适合您,而不是忽略它们:
interface IAuthLoginResponse {
message: string;
success: boolean;
errors: any;
}
...
login( loginData ): Promise<IAuthLoginResponse> {
return new Promise<IAuthLoginResponse>(function (resolve, reject) { ... })
}