【问题标题】:variable not resolve when pass through super from child class从子类通过超级时变量无法解析
【发布时间】:2018-07-13 17:45:06
【问题描述】:

这是我的数据服务类

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);
 }
}

我在这里的子类中使用 DataService

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);
 }
}

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

这里是URL,它是从未解析的子类传递的

我已经完成了类似问题herehere中提到的答案,但没有帮助我,我不知道这里做错了什么,

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

任何帮助都会非常感谢

【问题讨论】:

  • 尝试从DataService 中删除@Injectable(),并且不要在提供程序中列出DataService。 IMO 它只是一个基类,Angular 不必关心它。
  • @hgoebl 非常感谢您救了我先生,我试图从过去 2 天解决这个问题
  • 我添加了一个完整的答案,因为我认为很多人可能会对此感到困惑。

标签: angular typescript heroku


【解决方案1】:

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 服务。

【讨论】:

    猜你喜欢
    • 2018-11-20
    • 1970-01-01
    • 2012-10-08
    • 1970-01-01
    • 2013-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-05
    相关资源
    最近更新 更多