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?
@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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With