我创建了CustomHttp类,它像这里一样扩展了Http:http://restlet.com/blog/2016/04/18/interacting-efficiently-with-a-restful-service-with-angular2-and-rxjs-part-3/#comment-83563
我将提供程序添加到bootstrap中:
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]
},
])
所有覆盖方法(获取,发布等)都可以正常工作。然后我将自定义属性和方法添加到CustomHttp类,并尝试访问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
}
}
如何访问CustomHttp的自定义方法和属性?
答案 0 :(得分:5)
您可以通过将Http
实例强制转换为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);
}
(...)
}
使用以下CustomHttp
类:
@Injectable()
export class CustomHttp extends Http {
someProperty:string = 'some string';
(...)
}
答案 1 :(得分:0)
import {Http} from '@angular/http';
import {CustomHttp} from '/path';
export class MainComponent {
constructor(private _http: CustomHttp) {
this._http.getCustomProperty();
}
}