angular - Utöka http-klassen och få tillgång till egna egenskaper (Angular2 TypeScript)
Jag skapade CustomHttp-klassen som utökar Http som här: http://restlet.com/blog/2016/04/18/interacting-efficiently-with-a-restful-service-with-angular2-and-rxjs-part-3/#comment-83563
Jag lade till leverantörer till bootstrap på detta sätt:
bootstrap([
HTTP_PROVIDERS,
{ provide:Http,
useFactory: (backend: XHRBackend, defaultOptions: RequestOptions, errorNotifier: NotificationHandlerService,
authService: AuthInfoService) => {
return new CustomHttp(backend, defaultOptions, errorNotifier, authService);
},
deps: [ XHRBackend, RequestOptions, NotificationHandlerService, AuthInfoService]
},
])
Alla överskuggade metoder (get, post, etc.) fungerar bra. Sedan lade jag till en anpassad egenskap och metod i CustomHttp-klassen och försökte komma åt egenskapen utanför CustomHttp:
@Injectable()
export class CustomHttp extends Http {
...
private myCustomProperty = 'It`s custom';
public getCustomProperty() {
return this.myCustomProperty;
}
...
}
=====================
import {Http} from '@angular/http';
export class MainComponent {
constructor(private _http: Http) {
this._http.getCustomProperty(); // this method doesn`t exist in Http
}
}
Hur kan jag få åtkomst till anpassade metoder och egenskaper på CustomHttp?
Svar #1
Du kan försöka med följande genom att kasta Http-instansen till CustomHttp:
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { CustomHttp } from './custom.http';
@Injectable()
export class BooksService {
constructor(private http:Http) {
console.log((<CustomHttp>this.http).someProperty);
}
(...)
}
med följande CustomHttp-klass:
@Injectable()
export class CustomHttp extends Http {
someProperty:string = 'some string';
(...)
}
Svar #2
import {Http} from '@angular/http';
import {CustomHttp} from '/path';
export class MainComponent {
constructor(private _http: CustomHttp) {
this._http.getCustomProperty();
}
}
