如何将注册回调转换为Observable,符合Angular 2约定?这就是回调结构的样子
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());
});
解决方法:
有一个RxJS静态运算符就是为了这个目的:bindNodeCallback
.它将一个Node风格的回调API转换为一个返回Observable的函数.
你会这样使用它:
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)
);
请注意,您需要调用bind以将signUp绑定到userPool.