gpt4 book ai didi

javascript - Angular 2 和原生 Promise

转载 作者:行者123 更新时间:2023-12-03 05:18:23 27 4
gpt4 key购买 nike

我在使用带有第二个 Angular 和 typescript 的 native promise 时遇到问题:

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 ...
}

尝试搜索我必须采取的措施来解决类型“{}”上不存在属性“成功”。错误,但没有成功。

最佳答案

发生这种情况是因为上面的代码没有输入。

为了使这项工作正常进行,它应该是

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) { ... })
}

关于javascript - Angular 2 和原生 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41508709/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com