2017-04-06 48 views
2

我可以肯定地图中可见,可变换我喜欢的任何方式的反应,但经历了documentation而我碰到如何在向JSON的HTTP请求之后通过angular-in-memory-web-api来变形返回到Observable的响应?

responseInterceptor

所以来了,我不知道如果我可以把一些配置,并得到一个JSON响应本身无需编写我的额外功能。

关于responseInterceptor或如何使用它没有多少书面。 如果不是这样,那么是否有其他方式使用angular-in-memory-web-api本身来执行此操作?

回答

1

之前它返回到可观察到的这种拦截器的帮助下

You can morph the response returned by the default HTTP methods, called by collectionHandler , to suit your needs by adding a responseInterceptor method to your InMemoryDbService class. The collectionHandler calls your interceptor like this:

responseOptions = this.responseInterceptor(responseOptions, requestInfo); 

为了测试它的工作,你可以将此代码添加到您可以修改响应您的InMemoryDbService

responseInterceptor(res: ResponseOptions, ri: RequestInfo):ResponseInterceptor { 
    console.log("call responseInterceptor"); 
    return res; 
} 
+0

在测试上述内容时,我看到'ResponseOptions'类型的'res'返回,但函数期望'ResponseInterceptor'类型返回。这也被我的typeScript标记。 –

+0

我正在尝试你的建议,在'responseInterceptor()'我看到'res'内部,我修改它并使用res中的数据创建不同的JSON对象并返回新创建的'object'。但是我做HTTP请求的地方说:'http.get(url).map(reponse => // somecode)。 catch((error)=> log error //)'。我一直得到这个错误:'{“ok”:false,“statusText”:“未知状态”,“url”:“api/sessionData/1”}'。我究竟做错了什么?不应该修改responseInterceptor()的返回值? –

+0

嘿,它的工作我猜。稍后会确认你。 –

0

Angular的内存中web-api和ResponseInterceptor用于在测试场景中伪造/操纵请求。

毕竟,我不清楚,你的目的是什么。

+0

如果拦截XHR调用,不应该是'requestInterceptor'吗?我只想知道是否有一种方法可以在HTTP请求(由angular-in-memory-web-api处理)之后返回JSON(仅仅是因为我遇到了'responseInterceptor')而不是一个Observable。 –

+0

你说得对,我想。我更新了我的答案。尽管如此,你试图达到的目标并不十分清楚。你可能有一些代码可以告诉我们吗?这将有助于让事情更清楚。 – Hinrich

+0

我想修改返回的observable中包含的数据'(response)'。让它像我想要的JSON格式。所以我猜,这可以在'responseInterceptor()'内完成。 –

相关问题