How to inject or use Http inside static method in angular 2 final service?
Asked Answered
M

3

6

I am using Angular 2 final version. I have a validator service in Angular 2. I am writing a static method for asynchronous validation which uses HttpModule. So in this context, how to inject and use Http, so that I can make a call to backend. I tried making a declaration like below: static http:Http;

then tried to use inside static method like ValidationService.http.get() But that is throwing error like- get is undefined.

Can somebody throw some light into this?

Madelyn answered 18/11, 2016 at 21:12 Comment(0)
A
5
@NgModule(...)
class AppModule {
  ngDoBootstrap(moduleRef) {
    let injector =  moduleRef.injector;
    // assign injector somewhere to a static field
  }
}

then you can use it like

someStaticMethod() {
  let validationService = someStatic.injector.get(ValidationService);
}

You should try to avoid static methods though. They are against Angular2s architecture.

Adrenaline answered 18/11, 2016 at 21:25 Comment(3)
Thanks ,then i think I should change static. I think I should google more about this.Madelyn
Can you elaborate on the solution? I'm experiencing a similar issue with the validation service and have been following this tutorial link to create validations for a form. When injecting http to the service, I get undefined. I'm a bit unfamiliar with static functions and not sure if that is the reason why it's not working?Jonathanjonathon
How is a validation service related to static method? It might be better to create a new question where you add the code that demonstrates what you try to accomplish.Valor
A
1

I followed this post (http://www.adonespitogo.com/articles/angular-2-extending-http-provider/) to extends Http class and added an static method which returns a singleton of Http.

./services/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 {}

./services/validation.service.ts

import CustomHttp from './http.service';

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

I hope it works for you.

Amigo answered 1/8, 2017 at 12:29 Comment(0)
P
1

I use angular-starter framework and I get access to injector in src/app/app.module.ts file in:

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

And somewhere in static method of your OtherStaticClass you write:

SomeStaticClass.angularInjector.get(ValidationService);
Paddie answered 7/10, 2017 at 9:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.