我正在用Angular 5编写一个应用程序,对于某些功能来说,在我的http调用之后添加诸如finally块之类的功能非常重要。
我不确定如何使用Observables来执行此操作,因为Observable中没有final函数:http://xgrommx.github.io/rx-book/content/observable/observable_methods/index.html
code snippet:
getInfo() {
const params = new HttpParams()
.set('username', 'swapp')
.set('password', "test");
return this.http
.get('myurl', {params: params})
.catch(this.errorHandler);
}
答案 0 :(得分:1)
您可以使用intercepter
:
http_intercepter.ts:
import { Injectable, Injector } from '@angular/core';
import {
HttpEvent,
HttpHeaders,
HttpInterceptor,
HttpResponse,
HttpErrorResponse,
HttpHandler,
HttpRequest
} from '@angular/common/http';
import { AppService } from './../app.service';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
@Injectable()
export class MyInterceptor implements HttpInterceptor {
constructor(
private appService: AppService,
) {
}
/**
*
* @param req - parameter to handle http request
* @param next - parameter for http handler
*/
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const started = Date.now();
/**
* Handle newly created request with updated header (if given)
*/
return next.handle(req).do((event: HttpEvent<any>) => {
/**
* Sucessfull Http Response Time.
*/
if (event instanceof HttpResponse) {
const elapsed = Date.now() - started;
}
}, (err: any) => {
/**
* redirect to the error_handler route according to error status or error_code
* or show a modal
*/
if (err instanceof HttpErrorResponse) {
switch (err.status) {
case 400:
console.log("400 type")
break;
case 401:
console.log("401 type")
break;
case 404:
console.log("404 type");
break;
default:
break;
}
}
});
}
}
app.module.ts:
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: MyInterceptor,
multi: true,
},
]
答案 1 :(得分:0)
如@UnluckyAj所说,您可以在INTERCEPTORS中集中处理catch http失败,或者如果您想在每个调用中进行细化操作,请尝试类似以下操作:
getInfo(){
floor()
}
如果您想要“最终阻止”,请尝试:
const params = new HttpParams()
.set('username', 'swapp')
.set('password', "test");
return this.http
.get('myurl', {params: params})
.subscribe(this.onsuccessHandler,this.errorHandler); // FIRST function is for success SECOND for failure
答案 2 :(得分:0)
我找到了一种将final块添加到Observable的方法。
导入'rxjs / add / operator / finally';
return this.http
.get(CONSTANT.ENV.prod.url.concat(endpoint), {params: params})
.catch(this.errorHandler)
.finally(this.handleFinally)