gpt4 book ai didi

typescript - 扩展 http 类并访问自定义属性(Angular2 typescript )

转载 作者:太空狗 更新时间:2023-10-29 18:17:09 24 4
gpt4 key购买 nike

我创建了扩展 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com