私はこのポスト(http://www.adonespitogo.com/articles/angular-2-extending-http-provider/)を拡張してHttpクラスを拡張し、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);
})
}
}
私はそれがあなたのために働くことを望む。
おかげで、その後、私は思う:あなたの
OtherStaticClass
あなたが書くの静的メソッドのどこかにそして、私は静的を変えるべきです。私はこれについてもっとGoogleにすべきだと思う。 – revathi
あなたは解決策を詳しく述べることができますか?私は検証サービスで同様の問題を経験しており、このチュートリアル[https://coryrylan.com/blog/angular-form-builder-and-validation-management]に従ってフォームの検証を作成しています。サービスにhttpを注入すると、私は定義されません。私は静的関数にはなじみがなく、なぜそれがうまくいかないのかわからないのですか? – PBandJen
検証サービスは静的メソッドにどのように関連していますか?あなたが達成しようとしていることを示すコードを追加する新しい質問を作成する方が良いかもしれません。 –