简体   繁体   English

Observable.of无法在HttpClient拦截器中按预期方式工作

[英]Observable.of does not work as expected in HttpClient Interceptor

Problem 问题

The Observable.of convert arguments to an observable sequence means it can be used as a mock response to another Observable which is subscribe. Observable.of转换为可观察序列的参数意味着可以将其用作对另一个订阅的Observable的模拟响应。 But now, It seems Observable.of does not work when its called from an interceptor because methods which are subscribing to it does not execute 但是现在,当从拦截器中调用Observable.of时,它似乎无法工作,因为预订该方法的方法无法执行

Expected behavior: 预期行为:

When Observable.of is called with the given data, the HttpClient should return the data to the method which is already subscribing to it 当使用给定的数据调用Observable.of时, HttpClient应该将数据返回到已经预订的方法中

Demo 演示

Live Demo (open DevTools console to read logs) 现场演示 (打开DevTools控制台以读取日志)

There is a service ( mock.service.ts ) which makes a mock HTTP get request using HttpClient , the request arrives at mock.interceptor.ts and it want's to answer with the mock data using Observable.of (means wants to not let the request to goes over the network), the mock.service has a subscriber in app.component which is waiting for the response of the HttpClient . 有一个服务( mock.service.ts )使用HttpClient发出模拟HTTP get请求,该请求到达mock.interceptor.ts并且它希望使用Observable.of来响应模拟数据(意味着不要让请求越过网络),则mock.service具有在订户app.component其正在等待的响应HttpClient No data arrives in subscriber, nor error. 没有数据到达订户,也没有错误。

Any idea about how to implement interceptor that works with Observable.of ? 关于如何实现与Observable.of一起使用的拦截器的任何想法?

Try to change the return statement in interceptor intercept method to: 尝试将拦截器拦截方法中的return语句更改为:

return Observable.of( new HttpResponse<any>( { body: mockData }))

Live Demo 现场演示

Observable.of is depricated use Observable.create instead Observable.of是depricated使用Observable.create代替

return Observable.create((ob) => {
      ob.next(new HttpResponse<any>({body: data}));
});

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

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