GCS*_*SDC 2 javascript rxjs amazon-cognito angular
我正在使用 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);
}
});
}
Run Code Online (Sandbox Code Playgroud)
现在,我不想直接在服务上使用回调,而是想从 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();
}
});
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
665 次 |
| 最近记录: |