Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 942
revathi Avatar asked Nov 18 '16 21:11

revathi


2 Answers

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

like image 169
Günter Zöchbauer Avatar answered Sep 28 '22 04:09

Günter Zöchbauer


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.

like image 23
jcamelis Avatar answered Sep 28 '22 04:09

jcamelis