我要创建Cognito用户并同时将用户分配给用户组。当您必须创建一个可观察对象时,对我来说很好。但是当有必要创建一个发出两个请求的可观察对象时,我将无法工作。我认为我们需要使用forkJoin
或flatMap
。我使用Angular 7,所以使用RxJs 6.x。
创建代码,确定:
createUser(user: User): Observable<User[]> {
const _self = this;
const cognitoidentityserviceprovider = new AWSCognito.CognitoIdentityServiceProvider({
credentials: this.getCognitoCreds()
});
const params = {
UserPoolId: this.poolData.UserPoolId,
Username: user.username,
DesiredDeliveryMediums: [ 'EMAIL' ],
ForceAliasCreation: false,
MessageAction: 'SUPPRESS',
TemporaryPassword: '1234fooo*',
UserAttributes: [
{
Name: 'email',
Value: user.email
}
]
};
return Observable.create(obs => {
cognitoidentityserviceprovider.adminCreateUser(params, function(error, data) {
if (error) {
console.log(error);
return Observable.throw(error || 'Server error');
} else {
console.log(data);
//
//
// HERE user is create :)
// I want add to group here (see code down in this post)
//
//
return obs.next(data);
}
});
});
}
添加组代码,确定:
const p = {
GroupName: 'admin',
UserPoolId: _self.poolData.UserPoolId,
Username: user.username
};
return Observable.create(o => {
cognitoidentityserviceprovider.adminAddUserToGroup(p, function(err, d) {
if (err) {
console.log(err);
return Observable.throw(err || 'Server error');
} else {
console.log(d);
return o.next(d);
}
});
});
答案 0 :(得分:0)
我将第一个可观察变量放入const,然后返回此可观察变量.pipe(mergeMap((u:CognitoUser)=> {2nd observable
}
createUser(user: User): Observable<User[]> {
const _self = this;
const cognitoidentityserviceprovider = new AWSCognito.CognitoIdentityServiceProvider({
credentials: this.getCognitoCreds()
});
const params = {
UserPoolId: this.poolData.UserPoolId,
Username: user.username,
DesiredDeliveryMediums: [ 'EMAIL' ],
ForceAliasCreation: false,
MessageAction: 'SUPPRESS',
TemporaryPassword: '1234Fooo*',
UserAttributes: [
{
Name: 'email',
Value: user.email
}
]
};
const o = Observable.create(obs => {
cognitoidentityserviceprovider.adminCreateUser(params, function(error, data) {
if (error) {
console.log(error);
return Observable.throw(error || 'Server error');
} else {
console.log(data);
return obs.next(data.User);
}
});
});
return o.pipe(mergeMap((u: CognitoUser) => {
const p = {
GroupName: 'admin',
UserPoolId: _self.poolData.UserPoolId,
Username: u.Username
};
return Observable.create(ob => {
cognitoidentityserviceprovider.adminAddUserToGroup(p, function(err, d) {
if (err) {
console.log(err);
return Observable.throw(err || 'Server error');
} else {
console.log(d);
return ob.next(d);
}
});
});
}));
}