任何人都可以在this._getReactions$.next()
遇到错误时this.http.get(...)
不起作用的情况下提供帮助。我想保持可观察状态,以便进行下一次输入。
private _getReactions$: Subject<any> = new Subject();
constructor() {
this._getReactions$
.pipe(
switchMap(() => {
return this.http.get(...)
// http request
}),
catchError(error => {
console.log(error);
return empty();
})
)
.subscribe(data => {
console.log(data)
//results handling
});
}
onClick() {
this._getReactions$.next();
}
答案 0 :(得分:3)
如果可观察的死亡将其称为错误处理程序,并且它们已关闭,则您无法通过它们发送任何消息,这意味着它们已关闭,包括间隔已死的上游所有内容。
如果我们想生活。
隐藏主要观察者链是解决方案
在switchmap
内捕获
每当触发请求switchmap
创建可观察的ajax,这次使用
catch
。
switchmap
的行为表明我的出处
还没有完成,所以我真的不在乎孩子
完成我要继续前进。
constructor() {
this._getReactions$
.pipe( tap(value=>{this.loading=true; return value}),
switchMap(() => {
return this.http.get(...).pipe(
catchError((error)=>this.handleError(error)))
// http request
}),
)
.subscribe(data => {
console.log(data)
//results handling
this.error=false;
this.loading=false
});
}
private handleError(error: HttpErrorResponse) {
this.error = true;
console.log(error)
this.loading = false
return empty();
}
答案 1 :(得分:1)
我已经为所有请求
解决了这个问题创建一个加载器文件,所有请求都将在其中执行
loader.ts
import { Observable, Subject, Subscription, EMPTY } from 'rxjs';
import { catchError, map, switchMap } from 'rxjs/operators';
export class Loader<T1, T> {
private _requestQueue: Subject<T1>;
private _errorQueue: Subject<Error>;
private _resultQueue: Observable<T>;
private _loaded = false;
constructor(loaderFunction: (T1) => Observable<T>) {
this._requestQueue = new Subject<T1>();
this._errorQueue = new Subject<Error>();
this._resultQueue = this._requestQueue.pipe(
switchMap(_ => {
this._loaded = false;
return loaderFunction(_).pipe(
catchError(error => {
this._loaded = true;
this._errorQueue.next(error);
// Returning EMPTY observable won't complete the stream
return EMPTY;
})
);
}),
map(_ => {
this._loaded = true;
return _;
}),
);
}
public load(arg?: T1): void {
this._requestQueue.next(arg);
}
public subscribe(successFn: (T) => any, errorFn?: (error: any) => void,
completeFn?: () => void): Subscription {
this._errorQueue.subscribe(err => {
errorFn(err);
});
return this._resultQueue.subscribe(successFn, null, completeFn);
}
public complete() {
this._requestQueue.complete();
this._errorQueue.complete();
}
get loaded(): boolean {
return this._loaded;
}
}
在您将要执行请求的其他文件中(简单)
export class Component {
readonly loader: Loader<ResponseType, RequestParamType>;
constructor() {
this.loader = new Loader(param => this.http.get(param));
this.loader.subscribe(res => {
// Your stuffs
}, (error) => {
// Error Handling stuffs
}, () => {
// on Complete stuffs (Optional)
});
}
ngOnInit() {
this.loadData();
}
loadData() { // Call this function whenever you want to refresh the data
this.loader.load(params); // this param will directly passed to the http request
}
}
我在加载器中定义了其他参数,可以帮助你喜欢加载状态和完成流的选项(在 ngOnDestroy 中)
快乐编码!