variable not resolve when pass through super from child class

时间:2018-02-03 09:45:40

标签: angular typescript heroku

Here is my data Service class

import { BadInput } from './../common/bad-input';
import { NotFoundError } from './../common/not-found-error';
import { AppError } from './../common/app-error';
import { Http } from '@angular/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/throw';

@Injectable()
export class DataService {
 constructor(private url: string, private http: Http) { }

  getAll(obj) {
return this.http.post(this.url+"/get",obj)
  .map(response => response.json())
  .catch(this.handleError);
}
 customQuery(query) {
  console.log(this.url+"/dynamic/"+query);
return this.http.get(this.url+"/dynamic/"+query)
  .map(response => response.json())
  .catch(this.handleError);
 }
}

Am using DataService in child class here

import { Injectable } from '@angular/core';
import { DataService } from "./data.service";
import { Http } from "@angular/http";

@Injectable()
export class ReasonsService extends DataService {
  constructor(http: Http) {
  super("xxx/v1/reasons", http);
 }
}

ERROR in : Can't resolve all parameters for DataService in /tmp/build_b7eed86c18aa452fb03d88946e269f3a/toshikverma-rentitnow-df48c05/src/app/services/data.service.ts: (?, [object Object]).

Here URL which is passed from child class in not resolved

I have gone through the answers mentioned on the similar question here and here, but didn't help me, I don't know what mistake am doing here,

 "postinstall": "ng build --aot -prod",

Any help would be great thanks

1 个答案:

答案 0 :(得分:0)

TL; DR

仅使用@Injectable注释派生就足够了,并在providers[]中列出它们,而不是基类。

代码

// NOTE: no @Injectable() here!
export class DataService { // might be abstract to reinforce meaning
  constructor(private url: string,
              protected http: Http) { }

  getAll(obj) { ... }
  customQuery(query) { ... }
}


@Injectable()
export class ReasonsService extends DataService {
  constructor(http: Http) {
    super("xxx/v1/reasons", http);
  }
}

解释

您的基类DataService不是由Angular实例化和管理的服务。它只是您ReasonsService等其他服务的基类。

因此,您的基类DataService不得包含@Injectable()注释,且不应列在providers中。

换句话说:继承基类与Angular无关,它是TypeScript的东西。

评论

  • 您可以考虑将基类声明为abstract。通过这一点,每个人都可以看到这个类不会被它自己实例化,只是作为一个基类。
  • 如果您需要在派生中在基类中声明的成员,请将它们protected而不是private。例如,您也可以访问派生类中的http服务。