取消 http.put()/http.get() 和 return 值而不是 creating/sending 请求
Cancel http.put()/http.get() and return value instead of creating/sending request
给定以下代码:
服务:
getList(){
return return this.http.request("put", url_, options_)
}
组件:
submitRequest(reset?){
this.httpService.getList().subscribe((response) => {
//if reset return an empty array
//server cannot return an empty array
})
}
我想做类似的事情:
组件:
submitRequest(reset?){
this.httpService.getList().pipe(someOperator(() => {
// if reset DO NOT MAKE HTTP CALL BUT INSTEAD RETURN []
})).subscribe((response) => {
//IF reset NO SERVER CALL WAS MADE BUT GOT [] FROM someOperator
//SERVER RESPONSE ONLY IF NO reset
})
}
我如何使用 RXJS 实现此目的?
类似于:if (reset) return of([])
?
submitRequest(reset?){
if (reset) return of([])
this.httpService.getList().pipe(someOperator(() => {
// if reset DO NOT MAKE HTTP CALL BUT INSTEAD RETURN []
})).subscribe((response) => {
//IF reset NO SERVER CALL WAS MADE BUT GOT [] FROM someOperator
//SERVER RESPONSE ONLY IF NO reset
})
}
我会将 reset
运算符更改为 Observable<any>
,它 而不是 在订阅时立即发出任何内容(例如,不是 BehaviorSubject),然后代码可以更改为:
private destroy$: Subject<void> = new Subject();
ngOnDestroy(): void {
this.destroy$?.next();
this.destroy$?.complete();
}
submitRequest(reset?: Observable<any>){
let o$ = this.httpService.getList();
if (reset) {
o$ = merge(o$, reset.pipe(mapTo([])));
}
o$.pipe(
first(),
takeUntil(destroy$)
).subscribe(response => whatever);
}
订户功能将
- 如果您的
this
被摧毁,则不会被调用。否则,
如果 reset
在收到服务器响应之前发出任何内容,- 将收到一个空数组。否则
- 收到服务器响应。
在任何这些情况下,订阅将被取消,因此它会自行清理。
给定以下代码:
服务:
getList(){
return return this.http.request("put", url_, options_)
}
组件:
submitRequest(reset?){
this.httpService.getList().subscribe((response) => {
//if reset return an empty array
//server cannot return an empty array
})
}
我想做类似的事情:
组件:
submitRequest(reset?){
this.httpService.getList().pipe(someOperator(() => {
// if reset DO NOT MAKE HTTP CALL BUT INSTEAD RETURN []
})).subscribe((response) => {
//IF reset NO SERVER CALL WAS MADE BUT GOT [] FROM someOperator
//SERVER RESPONSE ONLY IF NO reset
})
}
我如何使用 RXJS 实现此目的?
类似于:if (reset) return of([])
?
submitRequest(reset?){
if (reset) return of([])
this.httpService.getList().pipe(someOperator(() => {
// if reset DO NOT MAKE HTTP CALL BUT INSTEAD RETURN []
})).subscribe((response) => {
//IF reset NO SERVER CALL WAS MADE BUT GOT [] FROM someOperator
//SERVER RESPONSE ONLY IF NO reset
})
}
我会将 reset
运算符更改为 Observable<any>
,它 而不是 在订阅时立即发出任何内容(例如,不是 BehaviorSubject),然后代码可以更改为:
private destroy$: Subject<void> = new Subject();
ngOnDestroy(): void {
this.destroy$?.next();
this.destroy$?.complete();
}
submitRequest(reset?: Observable<any>){
let o$ = this.httpService.getList();
if (reset) {
o$ = merge(o$, reset.pipe(mapTo([])));
}
o$.pipe(
first(),
takeUntil(destroy$)
).subscribe(response => whatever);
}
订户功能将
- 如果您的
this
被摧毁,则不会被调用。否则,
如果 - 将收到一个空数组。否则
- 收到服务器响应。
reset
在收到服务器响应之前发出任何内容,在任何这些情况下,订阅将被取消,因此它会自行清理。