我创建了扩展 Http 的 CustomHttp 类: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]
},
])
所有覆盖的方法(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';
(...)
}
关于typescript - 扩展 http 类并访问自定义属性(Angular2 typescript ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38438020/