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

标签 typescript angular

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

相关文章:

typescript - 自定义管道 ionic 3 |找不到管道

javascript - 如何导入 "PermissionStatus"?

angular - 如何用 Angular 制作汉堡菜单?

css - Sass 无法使用 "~"从 node_modules 文件夹导入

javascript - 如何在 TypeScript 中进行方法重载?

typescript - 你如何调试 Jest 测试?

typescript - Typescript 无法正确识别通用类型

Typescript 接口(interface)通用属性名称

javascript - Angular 5 应用程序无法在 IE11 中呈现

angular - 我们应该在哪里取消订阅 Angular 的 SwUpdate.available?