如何将注册回调转换为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());
});
答案 0 :(得分:4)
出于这个目的,有一个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
。
答案 1 :(得分:2)
在没有定义类型的情况下,绑定无法正常工作。
要使其正常工作,请尝试以下内容:
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);
}