将cognitoUser.authenticateUser回调转换为observable



我正在使用AWS Cognito Javascript SDK构建一个angular应用程序进行身份验证。

我有一个login方法的服务:

login(username: string, password: string): void {
const authData = {
Username: username,
Password: password
};
const authDetails = new AuthenticationDetails(authData);
const userData = {
Username: username,
Pool: userPool
};
this.cognitoUser = new CognitoUser(userData);
const self = this;
this.cognitoUser.authenticateUser(authDetails, {
onSuccess: self.onSuccess.bind(self),
onFailure: self.onFailure.bind(self),
newPasswordRequired: function(userAttributes, requiredAttributes) {
self.newPasswordRequired.next(true);
self.authIsLoading.next(false);
}
});
}

现在,我不想直接在服务上使用回调,而是想从login方法返回一个可观察的方法,我可以订阅该方法并获得身份验证的结果:成功、失败或需要新密码。

我看了Observable bindCallback和bindNodeCallback方法,也看了另一个问题,但不知道如何做到这一点。

如何做到这一点?

您可以返回新的Observable,并使用next((和error((激发观察者:

login(username: string, password: string): Observable<{ type: string, result: any }>{
const authData = {
Username: username,
Password: password
};
const authDetails = new AuthenticationDetails(authData);
const userData = {
Username: username,
Pool: userPool
};
this.cognitoUser = new CognitoUser(userData);
return new Observable<{ type: string, result: any}>(obs => {
this.cognitoUser.authenticateUser(authDetails, {
onSuccess: (result: any) => {
obs.next({ type: 'success', result: result });
obs.complete();
},
onFailure: (error: any) => obs.error(error),
newPasswordRequired: (userAttributes, requiredAttributes) => {
obs.next({ type: 'newPasswordRequired', result: [userAttributes, requiredAttributes] });
obs.complete();
}
});
});
}

最新更新