在 Angular 和 RxJS 中一一执行方法
Execute methods one by one in Angular and RxJS
this.userClient.getUser(userName)
.pipe(
concatMap(
user => {
this.user = user;
return this.userClient.setStatus(this.user.id, 'banned');
}
),
concatMap(
user => {
//set property...
return this.userClient.deleteImg(user.img);
}
),
mergeMap(
user => {
this.user = user;
return this.userClient.setGroup(user.id, 'test');
}
)
)
.subscribe(
user => {
//actions
},
error => ...
)
我希望我的方法被一个接一个地打开,而不是一次全部打开。我怎样才能做到这一点? forkJoin是唯一的出路?
只需使用switchMap
this.userClient.getUser(userName)
.pipe(
switchMap(
user => {
this.user = user;
return this.userClient.setStatus(this.user.id, 'banned');
}
),
switchMap(
user => {
//set property...
return this.userClient.deleteImg(user.img);
}
),
switchMap(
user => {
this.user = user;
return this.userClient.setGroup(user.id, 'test');
}
)
)
.subscribe(
user => {
//actions
},
error => ...
)
保留第一个 switchMap,然后 return 一个 concat。 concat 将对您想要的三个项目进行排序。 Concat 等到完成一个,然后执行下一个,依此类推。
您可以在 RxjS Concat docs
上找到有关 concat
的更多信息
this.userClient.getUser(userName)
.pipe(
switchMap(
user => {
this.user = user;
return concat(
this.userClient.setStatus(this.user.id, 'banned'),
this.userClient.deleteImg(user.img),
this.userClient.setGroup(user.id, 'test')
);
}
)
)
.subscribe(
([user]) => {
//actions
},
error => ...
)
他们在 an episode of the Angular Show 上描述了其中的一些 高阶映射运算符 。它可能有助于理解这些工作原理。
this.userClient.getUser(userName)
.pipe(
concatMap(
user => {
this.user = user;
return this.userClient.setStatus(this.user.id, 'banned');
}
),
concatMap(
user => {
//set property...
return this.userClient.deleteImg(user.img);
}
),
mergeMap(
user => {
this.user = user;
return this.userClient.setGroup(user.id, 'test');
}
)
)
.subscribe(
user => {
//actions
},
error => ...
)
我希望我的方法被一个接一个地打开,而不是一次全部打开。我怎样才能做到这一点? forkJoin是唯一的出路?
只需使用switchMap
this.userClient.getUser(userName)
.pipe(
switchMap(
user => {
this.user = user;
return this.userClient.setStatus(this.user.id, 'banned');
}
),
switchMap(
user => {
//set property...
return this.userClient.deleteImg(user.img);
}
),
switchMap(
user => {
this.user = user;
return this.userClient.setGroup(user.id, 'test');
}
)
)
.subscribe(
user => {
//actions
},
error => ...
)
保留第一个 switchMap,然后 return 一个 concat。 concat 将对您想要的三个项目进行排序。 Concat 等到完成一个,然后执行下一个,依此类推。
您可以在 RxjS Concat docs
上找到有关concat
的更多信息
this.userClient.getUser(userName)
.pipe(
switchMap(
user => {
this.user = user;
return concat(
this.userClient.setStatus(this.user.id, 'banned'),
this.userClient.deleteImg(user.img),
this.userClient.setGroup(user.id, 'test')
);
}
)
)
.subscribe(
([user]) => {
//actions
},
error => ...
)
他们在 an episode of the Angular Show 上描述了其中的一些 高阶映射运算符 。它可能有助于理解这些工作原理。