Javascript 使用flatMap订阅onComplete永不完成
我将Javascript 使用flatMap订阅onComplete永不完成,javascript,angular,typescript,rxjs,rxjs6,Javascript,Angular,Typescript,Rxjs,Rxjs6,我将angular6与rxjs6.2.2和rxjscompact 6.2.2一起使用 我有一个代码可以调用我的api服务来加载一些记录,这是: this.route.params .flatMap((params: Params) => { if (!params['id']) { return Observable.throwError('Id is not specified.'); } this.itemId = params['id'];
angular6
与rxjs6.2.2
和rxjscompact 6.2.2
一起使用
我有一个代码可以调用我的api服务来加载一些记录,这是:
this.route.params
.flatMap((params: Params) => {
if (!params['id']) {
return Observable.throwError('Id is not specified.');
}
this.itemId = params['id'];
this.isEditMode = true;
this.loadCategoryGroupCondition = new LoadCategoryGroupViewModel();
this.loadCategoryGroupCondition.id = [this.itemId];
this.loadCategoryGroupCondition.pagination = new Pagination();
return this.categoryGroupService
.loadCategoryGroup(this.loadCategoryGroupCondition);
})
.subscribe(
(loadCategoryGroupResult: SearchResult<CategoryGroup>) => {
console.log(loadCategoryGroupResult);
},
() => {},
() => {
console.log('Completed')
});
this.route.params
.flatMap((参数:参数)=>{
如果(!params['id']){
返回可观察。抛出者('未指定Id');
}
this.itemId=params['id'];
this.isEditMode=true;
this.loadCategoryGroupCondition=新的LoadCategoryGroupViewModel();
this.loadCategoryGroupCondition.id=[this.itemId];
this.loadCategoryGroupCondition.pagination=新分页();
返回此.categoryGroupService
.loadCategoryGroup(此.loadCategoryGroup条件);
})
.订阅(
(loadCategoryGroupResult:SearchResult)=>{
日志(loadCategoryGroupResult);
},
() => {},
() => {
console.log('Completed')
});
上面的代码可以打印从api服务返回的项目列表。这意味着已调用onSuccess
但是完整的方法被触发了。
我的代码有什么问题
谢谢,如前所述,
flatMap
操作符本身并没有完成其源代码。您正在使用this.route.params
作为源代码的可观察对象,这是长期存在的-它永远不会自己完成
要获得完成
通知,您可以使用take
等操作符。它将重新发出作为参数传递并随后完成的项目数。例如,如果您只想接收当前路由,而对源观测的进一步通知不感兴趣,请使用take(1)
,如:
this.route.params
.take(1)
.flatMap((params: Params) => {
另外,请注意,在RxJS 6+中推荐的实现方法是使用可管道操作符。这看起来是这样的:
this.route.params.pipe(
first(),
mergeMap((params: Params) => {
...
})
我还用新推荐的变体替换了操作符。为什么它会完成?你的标题是“永不完成”,但在你的问题中你说“但是完整的方法被触发了”,那么你期待什么,发生了什么?顺便说一句,throwError看起来很奇怪,在以前的rxjs中它是
可观察的。throw
在v6中它的justthrowError
…@MartinAdámek,我想显示两条消息:-第一条消息应该是:console.log(loadCategoryGroupResult); - 第二个应该是:console.log('Completed')我的实际情况是:-console.log(loadCategoryGroupResult)被调用。-console.log('Completed')不是因为this.route.params
从未完成。只有合并到链中的api调用。如果你想调用complete,你需要完成所有源代码的观察。我不知道上面提到的代码的用例是什么,但是如果params不发出任何值(因为路由不包含),那么使用first(而不是take(1))将发出错误。如果我错了,请纠正我。