如何在角度2最终服务中注入或使用静态方法中的Http?

时间:2016-11-18 21:12:39

标签: http angular final inject

我正在使用Angular 2最终版本。 我在Angular 2中有一个验证器服务。我正在编写一个静态方法,用于使用HttpModule的异步验证。所以在这个上下文中,如何注入和使用Http,以便我可以调用后端。我试着做出如下声明:     静态http:Http;

然后尝试使用内部静态方法,如ValidationService.http.get() 但这就是抛出错误,如未定义。

有人可以对此嗤之以鼻吗?

3 个答案:

答案 0 :(得分:2)

@NgModule(...)
class AppModule {
  ngDoBootstrap(moduleRef) {
    let injector =  moduleRef.injector;
    // assign injector somewhere to a static field
  }
}

然后你可以像

一样使用它
someStaticMethod() {
  let validationService = someStatic.injector.get(ValidationService);
}

你应该尽量避免使用静态方法。他们反对Angular2s架构。

答案 1 :(得分:1)

我按照这篇文章(http://www.adonespitogo.com/articles/angular-2-extending-http-provider/)扩展了Http类,并添加了一个返回Http单例的静态方法。

./服务/ http.service.ts

import { Injectable, ReflectiveInjector } from '@angular/core';
import {
    BaseResponseOptions,
    BaseRequestOptions,
    BrowserXhr,
    ConnectionBackend,
    CookieXSRFStrategy,
    Headers,
    Http as HttpParent,
    Request,
    RequestOptions,
    RequestOptionsArgs,
    Response,
    ResponseOptions,
    XHRBackend,
    XSRFStrategy
} from '@angular/http';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class CustomHttp extends HttpParent {

    public static getInstance() {
        if (!(this._instance instanceof CustomHttp)) {
            this._instance = ReflectiveInjector.resolveAndCreate([
                CustomHttp, BrowserXhr, XHRBackend,
                { provide: ConnectionBackend, useClass: XHRBackend },
                { provide: ResponseOptions, useClass: BaseResponseOptions },
                { provide: XSRFStrategy, useFactory: () => {
                        return new CookieXSRFStrategy();
                    }
                },
                { provide: RequestOptions, useClass: BaseRequestOptions }
            ]).get(CustomHttp);
        }
        return this._instance;
    }

    private static _instance: CustomHttp;
}

./ app.module.ts

import { NgModule } from '@angular/core';
import { HttpModule, RequestOptions, XHRBackend } from '@angular/http';
import { CustomHttp } from './services/http.service';

@NgModule({
    bootstrap: [
        AppComponent
    ],
    declarations: [
        AppComponent
    ],
    imports: [
        HttpModule
    ],
    providers: [
        {
            provide: CustomHttp,
            useFactory: (backend: XHRBackend, options: RequestOptions) => {
                 return new CustomHttp(backend, options);
            },
            deps: [XHRBackend, RequestOptions]
        };
    ]
})
export class AppModule {}

./服务/ validation.service.ts

import CustomHttp from './http.service';

export class ValidationService {
    static public doSomething() {
        CustomHttp.getInstance().get('some/api/').subscribe(
            (response) => {
                 console.log(response);
            })
    }
}

我希望它适合你。

答案 2 :(得分:0)

我使用angular-starter框架,我可以访问src/app/app.module.ts文件中的注入器:

@NgModule({
    bootstrap: [ AppComponent ],  // due this method ngDoBootstrap is never call so we will get injector in constructor.
    ...
})
export class AppModule
{

    constructor(public appRef: ApplicationRef,
                public appState: AppState,
                public injector: Injector)
    {
        SomeStaticClass.angularInjector =  injector;
    }
...
}

在你写的OtherStaticClass静态方法的某处:

SomeStaticClass.angularInjector.get(ValidationService);