I'm currently trying to create a custom XHRBackend
for my angular2 app. I want to catch all http responses with a 401 http response code (unauthorized) to redirect the user on the login-page. But here comes my problem: the DI is not able to load the Router
in my custom-backend.
@Injectable()
export class CustomXHRBackend extends XHRBackend {
constructor(
_browserXHR: BrowserXhr,
_baseResponseOptions: ResponseOptions,
_xsrfStrategy: XSRFStrategy,
private router : Router) {
super(_browserXHR, _baseResponseOptions, _xsrfStrategy);
console.log(router); // --> undefined
}
createConnection(request: Request) {
let xhrConnection = super.createConnection(request);
xhrConnection.response = xhrConnection.response.catch((error, caugth) => {
if(error.status === 401) {
//Do stuff with the new router
this.router.navigate(['/login']);
}
return Observable.throw(caugth);
});
return xhrConnection;
}
}
It seems like the DI still uses the metadata of the XHRBackend
, because the first 3 params are defined.
I created a plunkr, that demonstrates this issue: http://plnkr.co/edit/44imf9KpE06cIyQ395sg?p=preview
Note:
The plunkr is based on the angular2 router example, unfortunately I had not enough time to create a smaller one.
The important files are custom.backend.ts
and perhaps main.ts
.
Has someone an idea, why this is happening?
For this, I would extend the
Http
class instead. Here is a sample:and register it as described below:
Edit
I think you need to provide explicitly parameters using
useFactory
:See this plunkr: http://plnkr.co/edit/JK3q5nspZ434AeJJsUeJ?p=preview.