简体   繁体   English

如何在自定义rxjs运算符中调用角度服务?

[英]How can I call an angular service from within a custom rxjs operator?

I'm writing a custom rxjs operator to handle logging HttpClient response errors. 我正在编写一个自定义rxjs运算符来处理记录HttpClient响应错误。 My instinct is to put the custom operator in its own file that I'd just include where needed. 我的直觉是将自定义运算符放在自己的文件中,该文件仅在需要时包括在内。 However, that puts it out of the “Angular world” so how would it get access to my Angular logging service? 但是,这使它脱离了“ Angular世界”,因此它将如何访问我的Angular日志记录服务?

Interceptor is one possible solution. 拦截器是一种可能的解决方案。 Another alternative is create your own http service which i prefer 另一种选择是创建自己的http服务,我更喜欢

class Http{
   constructor(private http:HttpClient){}
   logging = (res)=>tap(res=>log(res))
   preIntercept(options)=>options
   post(options){ 
      options=preIntercept(options)
      return http.post(options).pipe(logging)
   } 
}

It just gives you more flexibility, and code are more explicit. 它只是为您提供了更大的灵活性,并且代码也更加明确。 With default interceptor you will run into a lot of if else cases because every http call is going through this centralized hub. 使用默认拦截器,您会遇到很多if else情况,因为每个http调用都通过此集中式中心。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM