依赖注入不会加载所有参数 [英] Dependency injection does not load all params

查看:109
本文介绍了依赖注入不会加载所有参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试为我的angular2应用创建自定义XHRBackend.我想用401 http响应代码(未授权)捕获所有http响应,以在登录页面上重定向用户.但这是我的问题: DI无法将Router加载到我的自定义后端中.

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;
    }
}

由于定义了前三个参数,因此DI似乎仍然使用XHRBackend的元数据.

It seems like the DI still uses the metadata of the XHRBackend, because the first 3 params are defined.

我创建了一个plunkr,它演示了此问题: http://plnkr.co/edit/44imf9KpE06cIyQ395sg?p =预览

I created a plunkr, that demonstrates this issue: http://plnkr.co/edit/44imf9KpE06cIyQ395sg?p=preview

注意:

plunkr是基于angular2路由器示例的,不幸的是我没有足够的时间来创建一个较小的. 重要文件是custom.backend.ts,也许是main.ts.

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?

推荐答案

为此,我将扩展Http类.这是一个示例:

For this, I would extend the Http class instead. Here is a sample:

@Injectable()
export class CustomHttp extends Http {
  constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
    super(backend, defaultOptions);
  }

  request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
    console.log('request...');
    return super.request(url, options).catch(res => {
      // do something
    });        
  }

  get(url: string, options?: RequestOptionsArgs): Observable<Response> {
    console.log('get...');
    return super.get(url, options).catch(res => {
      // do something
    });
  }
}

并按如下所述进行注册:

and register it as described below:

bootstrap(AppComponent, [HTTP_PROVIDERS,
    new Provider(Http, {
      useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) => new CustomHttp(backend, defaultOptions),
      deps: [XHRBackend, RequestOptions]
  })
]);

修改

我认为您需要使用useFactory明确提供参数:

I think you need to provide explicitly parameters using useFactory:

import {provide} from '@angular/core';
import {Router} from '@angular/router';
import { bootstrap }            from '@angular/platform-browser-dynamic';
import { AppComponent }         from './app.component';
import { APP_ROUTER_PROVIDERS } from './app.routes';
import {HTTP_PROVIDERS, Http,RequestOptions, XHRBackend, XSRFStrategy, BrowserXhr} from '@angular/http';
import {CustomXHRBackend} from './custom.backend';

bootstrap(AppComponent, [
  APP_ROUTER_PROVIDERS,
  HTTP_PROVIDERS,
  provide(XHRBackend, {
    useFactory: (browserXHR: BrowserXhr, requestOptions: RequestOptions, xsrfStrategy: XSRFStrategy, router: Router) => {
      return new CustomXHRBackend(browserXHR, requestOptions, xsrfStrategy, router);
    },
    deps: [BrowserXhr, RequestOptions, XSRFStrategy, Router]
  })
]);

请参阅以下代码: http://plnkr.co/edit/JK3q5nspZ434AeJJsUeJ?p=preview .

这篇关于依赖注入不会加载所有参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆