问题
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());
});
回答1:
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
.
回答2:
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);
}
来源:https://stackoverflow.com/questions/41925040/use-observable-for-aws-cognito-callback