Use Observable for AWS cognito callback

How can I turn the signup callback into an Observable, conforming to the Angular 2 convention? This is what the callback structure is like

userPool.signUp(this.artist.email, this.artist.password, attributeList, null, function(err, result) {
  if (err) {
    alert(err);
    return;
  }
  let cognitoUser = result.user;
  console.log(JSON.stringify(result));
  console.log('user name is ' + cognitoUser.getUsername());
});

Answers:

Answer

There is an RxJS static operator for just that purpose: bindNodeCallback. It will convert a Node-style callback API to a function that returns an Observable.

You'd use it like this:

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/bindNodeCallback';

let signInAsObservable = Observable.bindNodeCallback(
  userPool.signUp.bind(userPool)
);
let observable = signInAsObservable(
  this.artist.email,
  this.artist.password,
  attributeList,
  null
);
observable.subscribe(
  result => {
    let cognitoUser = result.user;
    console.log(JSON.stringify(result));
    console.log('user name is ' + cognitoUser.getUsername());
  },
  error => alert(error)
);

Note that you will need to call bind to bind signUp to userPool.

Answer

The binding won't work without defining a Type.

To make it working try something like below:

register(user: RegistrationUser): Observable<any> {
  let attributeList = [];

  let dataEmail = {
    Name: 'email',
    Value: user.email
  };
  let dataNickname = {
    Name: 'nickname',
    Value: user.name
  };
  attributeList.push(new CognitoUserAttribute(dataEmail));
  attributeList.push(new CognitoUserAttribute(dataNickname));

  let signUp = Observable.bindNodeCallback<string, string, any[], any[], any>(this.userPool.signUp.bind(this.userPool));

  return signUp(user.email, user.password, attributeList, null);
}

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.