【问题标题】:Extend http class and access custom properties (Angular2 typescript)扩展 http 类并访问自定义属性(Angular2 typescript)
【发布时间】:2016-11-21 03:18:30
【问题描述】:

我创建了 CustomHttp 类,它像这里一样扩展 Http:http://restlet.com/blog/2016/04/18/interacting-efficiently-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 的自定义方法和属性?

【问题讨论】:

    标签: typescript angular


    【解决方案1】:

    您可以通过将 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';
    
      (...)
    }
    

    【讨论】:

    • 它有效,谢谢!这样使用CustomHttp是不是好办法?
    • 不客气!我不确切地知道你的用例,但一般来说,我们会尝试将子类“隐藏”到 Http 一个......话虽如此,这样做并不是错误的。
    【解决方案2】:
    import {Http} from '@angular/http';
    import {CustomHttp} from '/path';
    
    export class MainComponent {
    
        constructor(private _http: CustomHttp) {
           this._http.getCustomProperty(); 
        }
    }
    

    【讨论】:

    • 请编辑更多信息。不建议使用纯代码和“试试这个”的答案,因为它们不包含可搜索的内容,也没有解释为什么有人应该“试试这个”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-23
    • 2019-06-29
    • 1970-01-01
    • 2016-12-06
    • 1970-01-01
    相关资源
    最近更新 更多