我创建了CustomHttp类,该类扩展了Http,例如:http ://restlet.com/blog/2016/04/18/interacting-ficiently-with-a-restful-service-with-angular2-and-rxjs-part-3/ #comment-83563
我将提供程序添加到引导程序中是这样的:
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]
},
])
所有覆盖的方法(get,post等)都可以正常工作。然后,我向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的自定义方法和属性?
您可以通过将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';
(...)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句