2016-07-18 2 views
3

Я создал класс CustomHttp, который проходит Http как здесь: http://restlet.com/blog/2016/04/18/interacting-efficiently-with-a-restful-service-with-angular2-and-rxjs-part-3/#comment-83563Расширение класса HTTP и пользовательский доступ свойства (Angular2 машинопись)

Я добавил поставщик загрузчика, как это:

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] 
    }, 
    ]) 

Все переопределены методы (получить, 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?

ответ

5

Вы можете попробовать следующее литье экземпляра 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'; 

    (...) 
} 
+0

Он работает, спасибо! Это хороший способ использовать CustomHttp, как это? – norweny

+0

Добро пожаловать! Я не знаю точно вашего варианта использования, но, как правило, мы пытаемся «скрыть» подкласс с «Http» одним ... Это, как говорится, не является ложным. –

0
import {Http} from '@angular/http'; 
import {CustomHttp} from '/path'; 

export class MainComponent { 

    constructor(private _http: CustomHttp) { 
     this._http.getCustomProperty(); 
    } 
} 
+3

Исправьте с дополнительной информацией. Только код и «попробуйте» ответы не приветствуются, поскольку они не содержат содержимого, доступного для поиска, и не объясняют, почему кто-то должен «попробовать это». – abarisone

Смежные вопросы