本文介绍了扩展http类并访问自定义属性(Angular2打字稿)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了CustomHttp类,该类扩展了Http,如下所示: http://restlet.com/blog/2016/04/18/interacting-ficiently-with-a-restful-service-with-angular2 -and-rxjs-part-3/#comment-83563

I created CustomHttp class which extends Http like here: http://restlet.com/blog/2016/04/18/interacting-efficiently-with-a-restful-service-with-angular2-and-rxjs-part-3/#comment-83563

我将提供程序添加到引导程序中是这样的:

I added providers to bootstrap like this:

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外部访问该属性:

All overriden methods(get, post, etc.) work fine. Then I added custom property and method to CustomHttp class and tried to access the property outside 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的自定义方法和属性?

How can I access custom methods and properties of CustomHttp?

推荐答案

您可以通过将Http实例强制转换为CustomHttp来尝试以下操作:

You could try the following by casting the Http instance to 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';

  (...)
}

这篇关于扩展http类并访问自定义属性(Angular2打字稿)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 10:02