代码之家  ›  专栏  ›  技术社区  ›  GCSDC

将cognitoUser.authenticateUser回调转换为observable

  •  2
  • GCSDC  · 技术社区  · 7 年前

    我正在使用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);
        }
      });
    }
    

    登录

    我看了一眼可观察到的东西 bindCallback bindNodeCallback question ,但不知道该怎么做。

    1 回复  |  直到 7 年前
        1
  •  5
  •   GCSDC    7 年前

    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();
          }
        });
      });
    }