【问题标题】:How to extend a class in TypeScript?如何在 TypeScript 中扩展一个类?
【发布时间】:2016-10-21 10:31:21
【问题描述】:

我的服务很少,里面有相同的代码:

 constructor (private http: Http) {
    //use XHR object
    let _build = (<any> http)._backend._browserXHR.build;
    (<any> http)._backend._browserXHR.build = () => {
        let _xhr =  _build();
        _xhr.withCredentials = true;
        return _xhr;
    };
}

我想将代码移动到单独的文件http_base_clas.ts并尽可能重用代码。这里是http_base_clas.ts:

import {Http} from '@angular/http';

export class HttpBaseClass {
    constructor ( http: Http) {
        //use XHR object
        let _build = (<any> http)._backend._browserXHR.build;
        (<any> http)._backend._browserXHR.build = () => {
            let _xhr =  _build();
            _xhr.withCredentials = true;
            return _xhr;
        };
    }
}

如何将 http_base_class 扩展为 auth_service.ts?

import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {Headers, RequestOptions} from '@angular/http';
import {Observable} from 'rxjs/Observable';

@Injectable ()

export class AuthenticationService {
result: {
    ok: boolean;
};
private verifyUrl = 'http:example.com;  

constructor (private http: Http) {

}
private authRequest (url) {
    let body = JSON.stringify({});
    let headers = new Headers({ 'Content-Type': 'application/json'});
    let options = new RequestOptions({
        headers: headers
    });
    return this.http.post(url, body, options)
        .map((res: Response) => res.json())
        .map(res => {
            this.result = res;
            return this.result.ok;
        });
    }
}

【问题讨论】:

    标签: typescript angular extend


    【解决方案1】:
    class AuthenticationService extends HttpBaseClass {
      constructor(http:Http) {
        super(http);
      }
    
      private authRequest (url) {
        ...
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-06-11
      • 2015-08-10
      • 2019-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-02
      • 1970-01-01
      • 2018-09-22
      相关资源
      最近更新 更多