我目前正在尝试XHRBackend
为我的 angular2 应用程序创建自定义。我想使用 401 http 响应代码(未经授权)捕获所有 http 响应,以在登录页面上重定向用户。但我的问题来了:DI 无法Router
在我的 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;
}
}
似乎 DI 仍然使用 的元数据XHRBackend
,因为定义了前 3 个参数。
我创建了一个 plunkr,演示了这个问题:http ://plnkr.co/edit/44imf9KpE06cIyQ395sg?p=preview
笔记:
plunkr 基于 angular2 路由器示例,不幸的是我没有足够的时间来创建一个更小的路由器。
重要的文件custom.backend.ts
可能是main.ts
.
有人知道,为什么会这样?