gund / ng-http-interceptor Goto Github PK
View Code? Open in Web Editor NEWHttp Interceptor library for Angular
License: MIT License
Http Interceptor library for Angular
License: MIT License
Right now I am adding http timeout individually in all http calls in angular like
this.http.get(baseApiUrl) .timeoutWith(AppConstants.httpTimeout,Observable.defer(() => Observable.throw(new Error(AppConstants.httpTimeoutMessage)))) .map(Utils.successHandler) .catch((err) => { return Utils.errorHandler(err); });
Is there any way I can make of use ng-http-interceptor , in such a way that I can add timeout to all http calls globally in httpInterceptor.request().addInterceptor method.
res.do line gives an error :
[ts] Property 'do' does not exist on type 'Observable'.
httpInterceptor.response().addInterceptor((res, method) => { return res.do(r => console.log(method, r)); });
Please help.
Thanks.
Getting this error when trying to include the module and trying to add interceptors
See how it is in angular: https://github.com/angular/angular/blob/master/modules/%40angular/core/package.json
main
in package.json should point to the bundle, while new property module
should point to es6 style index.js
.
Is there a way to append headers via intercepter?
Thanks.
This causes problems when building in different projects and requires users to ignore source maps.
Now source mapping url looks like this:
//# sourceMappingURL=D:/Projects/ng2-http-interceptor/index.js.map
but should be like this:
//# sourceMappingURL=index.js.map
Relative paths should be used.
we use ng-http-interceptor to inject authentication headers and handle some http errors (such as 401 and 403)
we updated to 2.0.3 and noticed that some calls are duplicated. for instance our feature "create new stuff" leads to have 2 new rows in the db or "delete stuff" generates two DELETE calls.
downgrading to 2.0.2 fixed the issue.
ng http uses cold observables, so we wonder if 2.0.3 somehow subscribe to calls leading to this critical problem.
The module works perfectly on modern browsers, but for example for Safari 9, I need to use the proxy polyfill. Unfortunately, that does not work.
Safari says: EXCEPTION: Uncaught (in promise): TypeError: Proxy polyfill does not support trap 'http'
I think that's because of the private Http object in the service.
injected import { HttpInterceptorModule, HttpInterceptorService } from 'ng-http-interceptor';
imported HttpInterceptorModule.noOverrideHttp() in app.module.ts
I am using InterceptableHttp instead of http (only for few calls). I don't want to replace http for all calls.
I am using import {InterceptableHttp} from 'ng-http-interceptor' in service.
Now each intercepted call is happening twice.
Is there a way that that intercepted call only happens once?
Currently request observable is shared with next config:
.multicast(new BehaviorSubject<Response>(null))
.refCount()
.filter(r => r !== null);
This behavior should be replaced with:
.publishLast().refCount()
There is really weird behavior in test coverage reports uploaded to coveralls.io.
In Travis CI setup there is command to report code coverage which seems to work as I can see all the builds in coveralls repo.
However there are no data regarding actual code and it's coverage percentage.
The command which responsible for sending coverage looks like this:
cat ./coverage/coverage.lcov | ./node_modules/coveralls/bin/coveralls.js -v
I checked if actual coverage.lcov
file exists on travis - and it does.
Also I tried to upload coverage from my local machine with no luck as well.
For now have no idea what is going wrong.
I'm just trying to import this into an ionic 2 rc-4 app. I npm installed this and proxy-polyfill. If I include HttpInterceptorService in either my class constructor (and don't even use it), or if I add it to @NgModule.imports, then I get a runtime error when the app starts:
Cannot convert undefined or null to object
Stack
TypeError: Cannot convert undefined or null to object
at hasOwnProperty (<anonymous>)
at Function.__webpack_require__.o (http://localhost:8100/build/main.js:60:103)
at Object.<anonymous> (http://localhost:8100/build/main.js:253049:67)
at __webpack_require__ (http://localhost:8100/build/main.js:20:30)
at Object.<anonymous> (http://localhost:8100/build/main.js:253127:70)
at __webpack_require__ (http://localhost:8100/build/main.js:20:30)
at Object.<anonymous> (http://localhost:8100/build/main.js:124508:79)
at __webpack_require__ (http://localhost:8100/build/main.js:20:30)
at Object.<anonymous> (http://localhost:8100/build/main.js:187013:95)
at __webpack_require__ (http://localhost:8100/build/main.js:20:30)
Ionic Framework: 2.0.0-rc.4
Ionic Native: 2.2.12
Ionic App Scripts: 0.0.48
Angular Core: 2.2.1
Angular Compiler CLI: 2.2.1
Node: 6.8.1
OS Platform: OS X El Capitan
Navigator Platform: MacIntel
User Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36```
This will enable some async work to be done before actual http response will be fired.
Public API changes (non breaking):
type RequestInterceptor = Interceptor<any[], any[] | Observable<any[]>>;
All handling of observables will be incapsulated within private HttpInterceptorService._interceptRequest()
method
Any guess what it can be? i am using webstorm and if i do ctrl+click on ProxyHandler i can go to the declaration in typescript/lib/lib.es2015.proxy.d.ts
When an HTTP request ends up with error Angular throws error downstream to Observable and since all interceptors registered via .flatMap() operator they are bypassed by error and never get called.
I need to intercept also error case so .catch() operator must be used where I will call same chain of registered interceptors as for normal response.
Is there a way to intercept errors? Currently httpInterceptor.request() and httpInterceptor.response() intercept the request and response, but if we need to intercept errors, is there a method that can help do this?
The README mentions that returning false in an interceptor cancels the request but I'm getting the following typing error:
Argument of type '(data: any[], method: string) => false | any[]' is not assignable to parameter of type 'Interceptor<any[], any[] | Observable<any[]>>'.
Type 'false | any[]' is not assignable to type 'any[] | Observable<any[]>'.
Type 'false' is not assignable to type 'any[] | Observable<any[]>'.
with this piece of code:
httpInterceptor.request().addInterceptor((data, method) => {
if (!auth.email || !auth.token) return false;
const headers: Headers = getHttpHeadersOrInit(data, method);
headers.set('X-User-Email', auth.email);
headers.set('X-User-Token', auth.token);
return data;
});
Any ideas about what I'm doing wrong? Thanks!
interceptable-http.js:6Uncaught ReferenceError: __extends is not defined
at interceptable-http.js:6
at Object. (interceptable-http.js:19)
at webpack_require (bootstrap 01c23fe…:52)
at Object. (main.bundle.js:53937)
at webpack_require (bootstrap 01c23fe…:52)
at Object. (main.bundle.js:74782)
at webpack_require (bootstrap 01c23fe…:52)
at Object. (main.bundle.js:74739)
at webpack_require (bootstrap 01c23fe…:52)
at Object. (main.bundle.js:53991)
i see the helper functions but i am lost on how i am supposed to use them inside the interceptor to add a header.
or should i be calling a whole different method at the start ??
a small demo would be great!
So anybody curious about this lib will have brief insights of the possibilities included and what to expect from it.
Features worth highlighting:
Hey all,
first a big thanks for providing ng-http-interceptor.
It has a really nice and easy to understand API. ❤️
I want to test if my interceptions work as expected writing unit test.
Can you please provide some information how I have to override Http
in my TestBed configuration?
describe('When a http request timeout occurs', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
HttpModule,
HttpInterceptorModule
],
providers: [{
provide: Http,
useFactory: (mockBackend, options) => {
/*
* What do I have to do to override Http the right way?
*/
return new Http(mockBackend, options);
},
deps: [MockBackend, BaseRequestOptions]
}]
});
});
Many thanks in advance
Greg
How can I intercept responseError?
Hi I would like to know, how to handle cancellation of http request using ng-http-interceptor.
My current code.
`httpInterceptor.request().addInterceptor((data, method) => {
this.requestCount += 1;
if(!this.requestLoader){
this.requestLoader = true;
}
return data;
});
httpInterceptor.response().addInterceptor((res, method) => {
console.log(res,method);
return res.timeoutWith(
AppConstants.httpTimeout,
Observable.defer(() => {
this.decrementRequestCount();
return Observable.throw(new Error("Request Timeout"))
}
)
).do((data) => {
// console.log(method,data);
this.decrementRequestCount();
}, (error) => {
this.decrementRequestCount();
console.log("Http Error : "+ error);
})
});`
Here I am incrementing and decrementing the request , based on the request and response respectively. But when the request is cancelled, I am unable to handle it. Any help is appreciated
I install the latest version from NPM and getting following error on ng serve
Angular version - 4.0.1
Typescripit - 2.2.1
ERROR in .//ng-http-interceptor/dist/http/interceptable-http.js/ng-http-interceptor/dist/http/interceptable-http.js 1:0-33
Module not found: Error: Can't resolve 'tslib' in 'C:\source\Angular\client\node_modules\ng-http-interceptor\dist\http'
@ ./
@ .//ng-http-interceptor/dist/http/index.js/ng-http-interceptor/dist/index.js
@ ./
@ ./src/app/app.module.ts
@ ./src/main.ts
@ multi webpack-dev-server/client?http://localhost:4200 ./src/main.ts
this may not be an issue with the code in this package but i am putting a message here in case anyone knows what this is and how to fix it.
i have an app that is working 100% in chrome and Edge.
basic page load works in IE 11
web service calls that need a JWT fail.
IE 11 is not giving any errors during the app load.
the app is using the current angualr 4.xxx packages and is built with angualr-cli into packed scripts.
i am trying to determine the cause but right now i have no idea what the real problem is.
Starting from yesterday all tests on Travis CI are not executing.
As shown in this log: Executed 0 of 0 ERROR (0.008 secs / 0 secs)
It is really strange since nothing was changed since when it used to work in config nor in the source files.
And also I had run master branch build which was passing before and got same result.
Really weird stuff and for now have no idea how to fix it - all builds are just fail.
So that user can omit bundling stage if he do not need it and also this will give an option to serve library directly from CDN.
Required new bundles: UMD, UMD minified.
Builds shall not include their dependencies (ng2, rxjs, ...) but also require them from the environment.
This probably will require moving current unbundled version from dist
to lib
folder in order to place bundled browser ready version into dist
folder (yet unsure should I mix those or separate).
Regarding building tool most likely the choice will be on webpack, however I will look also closer to rollup and browserify and investigate what potential benefits I can get from them.
is it possible/planned to inject headers to the requests?
my use case is the following: basic authentication + auth data stored via redux. I would like to intercept all request and inject the Authorization header.
With automatic npm publish and github tags creation.
Also make sure all commits will not be done before tests and coverage won't be verified.
Next npm libraries shall be used:
I added this feature as per given instruction but getting following error in browser .
Uncaught ReferenceError: __extends is not defined
at interceptable-http.js:6
at Object. (interceptable-http.js:19)
at webpack_require (bootstrap b4bbcca…:52)
at Object. (main.bundle.js:77524)
at webpack_require (bootstrap b4bbcca…:52)
at Object. (main.bundle.js:77602)
at webpack_require (bootstrap b4bbcca…:52)
at Object. (main.bundle.js:15364)
at webpack_require (bootstrap b4bbcca…:52)
I need a feature that we can have an context object in interceptor interface, so we can share data between interceptors, especially between request interceptor and response interceptors(for example, the response interceptor can know the res is from which request)
so the interface will like this
export interface Interceptor<T, D> {
(data: T, method: string, context: any): D;
}
and the context is initialized as an empty object before go into the interceptor chain.
https://github.com/gund/ng2-http-interceptor/blob/master/src/http/interceptable-http-proxy.service.ts#L29
Is that make sense? If this enhancement is ok, I can make a PR to implement this feature.
Thank you.
I've still getting "ReferenceError: _extends ..." with typescrip v2.1.5 however I saw ts-helper is no longer needed after typescript 2.1. Just wondering do I still need ts-helper to get the interceptor working? Thanks!
So that everybody may know that contributions are welcomed =) and they can see what are the basic rules to follow to make our life easier and contributed PRs merged.
Some of the things to mention in the doc:
Probably it's a good idea to resolve this along with testing investigation so that no one will give up trying to commit something :)
First of all, good work so far!
Second, is there a way (or are you considering a way) to append headers to the request inside the interceptor. That is the main thing I would need an http-interceptor for and yours is the best one i have found so far. So you know, it would be nice =)
Thanks.
I was having a weird issue with Angular 4.2.6 on IE11... it was as if none of the polyfills were being recognized by the browser. As a result, the site completely broke and would not load. Errors in the console mentioned things like "Proxy" doesn't exist and "assign" is not a valid Object property... all things that the polyfills take care of...
I spent hours on this until, after a process of elimination in my code, I removed ng-http-interceptor. Suddenly, the site is working again.
Could you please show an example of response interceptors with forkJoin observable I'm not able to make it work.
I set my headers on request, and works fine, but I also would like to get the headers on every response, but couldn't figure it out.
Here is my request interceptor:
this.httpInterceptor.request().addInterceptor((data, method) => {
const headers = getHttpHeadersOrInit(data, method);
if (this.SESSION_COOKIE) {
headers.set('header1', this.SESSION_COOKIE);
}
return data;
});
I need to get the SESSION_COOKIE on every response. Could you please post an example?
Hi, I am struggling with an issue in which not all response headers are visible to the response handler. We have a large set of response headers that are not seeing at all:
this.httpInterceptor.response().addInterceptor((res, method) => {
return res.do(r => {
console.log('response interceptor:', r.headers);
let userInfoHeader = r.headers.get(this.appConfig.RESPONSE_USER_HEADER_NAME);
let sessionToken = r.headers.get(this.appConfig.RESPONSE_USER_HEADER_NAME);
In the snippet above, r.headers
only contains two of the headers, while all of the headers show up in the network console (Chrome). The ones that are not visible are CORS headers and some custom x-headers. Any help would be greatly appreciated.
I am running into an issue where every HTTP request is fired twice. All I did was include this library and use the HTTP_INTERCEPTOR_PROVIDER
. Everything else is standard angular2 http handling. Did anyone else experience this issue as well? If not, I will provide a plunker when I have more time
Hi! Sorry for asking here, how can i add default headers with this interceptor? Thanks
And possibilities to migrate testing from being running by angular-cli to plain karma/jasmine or even migrate to mocka/chai.
This does matter because tests run by ng cli takes quite large amount of time for the first run and that is used by git hook before every commit - so directly affects development experience and productivity.
I would like to add a timeout configuration on the request. If I extends the Http service, it's easy to add a timeout configuration on the Observable returned by the request method.
But I would like to use your library and on the request, we don't have any Observable on the request interceptors...is there any other way ?
Thx
Chrome works fine
but for IE 11, if I inject http module and this one, the error in console is
EXCEPTION: 'Proxy' is undefined
the code in App.component is very simple
constructor(private http: Http,
private httpInterceptor: HttpInterceptorService
) {
}
This is a minor nitpick, but this project requires RxJS ^5.3.0 while Angular requires ^5.0.1. So unless you're using some feature of RxJS >5.0.1, I suggest you require the same version.
rename to ng- as the number 2 going away...
Just by adding the following statement on my app.module file, production build with AOT fails.
import { HttpInterceptorModule } from 'ng-http-interceptor';
running production build, I am getting following error.
ERROR in D:/Projects/Git-Repos/ui/src/$$_gendir/node_modules/
ng-http-interceptor/dist/ng-http-interceptor.ngfactory.ts (10,26):
Cannot find module 'httpInterceptor'.
I have following in my dependencies
"ng-http-interceptor": "^3.1.0",
"proxy-polyfill": "^0.1.7",
and following in devdependencies
"tslib": "1.6.0",
Can you please help me know, what may I doing wrong?
i have tried a few times and it seems that in a feature module the interectptor does not get installed or called.
in my root level app.module it works as expected and i can see headers added to calls and logging in my console log when i call a rest api service.
but when i have a service in a feature module the interectptor is not working.
i tried adding the interecptor to the feature module and that does not add it.
what do i need to do to debug this or make this work for my entire application and all feature modules ?
I'm still seeing the ReferenceError: __extends is not defined
error. The project was generated using @angular/[email protected]
which includes TS2.1. According to the ts-helpers library it's not needed for TS>=2.1. I've tried both with and without the ts-helpers lib and i see the error either way. Anything I'm missing?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.