下面我尝试为401错误添加一些Angular2通用http错误处理,这些错误应该重新提示登录详细信息,然后再次重试http请求。
问题是重试不起作用,因为函数将在登录完成之前退出。我需要一种将两个或多个可观察量链在一起的方法。
我可以使用Typescripts async / await看到一种可能的方法,但我确定必须有一个RX样式的修复程序吗?
request(url: string, options?: RequestOptionsArgs, retry: boolean = true): Observable<Response> {
return this.http.request(url, options)
.catch(initialError => {
console.log(initialError);
if (initialError.status === 401) {
// load login screen, and re-auth
let login = new LoginDetails();
login.username = 'John';
login.password = 'John';
// this will call another observable to load a dialog form and get the credentials
this.apiAccountLoginPost(login)
.subscribe(data => {
// save session data
localStorage.setItem('session', data.toJSON());
// retry the http request again
return this.request(url, options); // need to promote this
}, error => {
// process error
return Observable.throw(initialError);
});
// TODO need to return the login retry as a Observable<Response>
答案 0 :(得分:0)
Observable.combineLatest(someObservable, anotherObservable).subscribe(response => {
console.log("this is array of responses: on 0 place you got response from 'someObservable, on 1 from 'anotherObservable'");
console.log(response);
});
但在你的情况下并非如此。你能做的就是:
private sendRequest(type: RequestType, url: string, optional?: RequestOptionsArgs, body?: any):Observable<Response> {
return Observable.create((subscriber: any) => {
someRequest.subscribe(val => {
console.log("correct one");
subscriber.next("push something");
}, (err) => {
console.log("error handling");
subscriber.next("push some error");
});
});
}
答案 1 :(得分:0)
我认为你应该这样做with rxjs/add/operator/retryWhen
或retry
您可以使用next
或error
方法来控制观察者。