如何在Angular 2中使此服务调用工作

时间:2018-02-01 07:32:09

标签: angular http

我正在尝试在基本服务类中执行所有http调用,只需从其他服务调用简单函数。

基本服务

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

@Injectable()
export class Base1Service {
constructor(private http: Http) {};

url = 'someUrl';

httpGet(uriContext: string, options?: any) {
  return this.http.get(this.url + uriContext, options)
      .timeout(something)
      .map(something)
      .catch(something);
}

httpPost(uriContext: string, request?: any, options?: any) {
    return this.http.post(this.url + uriContext, request, options)
      .timeout(something)
      .map(something)
      .catch(something);
}

}

其他服务

import 'rxjs/add/operator/toPromise';
import {Base1Service} from './base1.service';
import {Observable} from 'rxjs/Observable';
import {Headers, Http, RequestOptions, Response, Request, RequestMethod} 
from '@angular/http';

@Injectable()
export class OtherService extends Base1Service {
// constructor(private http: Http) {
//   super(http);
// }

getTheData(): Observable<any> {
   const uriContext = 'something';
   const param = {
      'something': something
   };
   const headers = new Headers({
      'X-locale': something,
      'Authorization': something
   });
   const options = new RequestOptions({headers: headers});
   return this.httpGet(uriContext, param, options);
}

这对我不起作用,我错过了什么吗? 如果我将Constructor与super()调用放在一起,则表示提供的参数与调用目标的任何签名都不匹配。 你能帮忙吗?我是Angular的新手。

2 个答案:

答案 0 :(得分:1)

您无法在TypeScript中覆盖私有类成员。

因此,您需要在两项服务中将private http: Http更改为protected http: Http

答案 1 :(得分:0)

只需使用以下代码替换其他服务

import 'rxjs/add/operator/toPromise';
import {Base1Service} from './base1.service';
import {Observable} from 'rxjs/Observable';
import {Headers, Http, RequestOptions, Response, Request, RequestMethod} 
from '@angular/http';

@Injectable()
export class OtherService {
 constructor(private _base1Service: Base1Service) {

}

getTheData(): Observable<any> {
   const uriContext = 'something';
   const param = {
      'something': something
   };
   const headers = new Headers({
      'X-locale': something,
      'Authorization': something
   });
   const options = new RequestOptions({headers: headers});
   return this._base1Service.(uriContext, param, options);
}