javascript - Angular2依赖注入(inject),类继承期间不注入(inject)服务

标签 javascript angular typescript dependency-injection

我正在使用 angular2Typescript。我正在尝试创建一个 base class ,它可以被其他类继承,并且在基类中,注入(inject)了一个服务。到目前为止,我无法将 ajaxService injected 正确地插入 base class 中,inherited用户类别。具体来说,当一个用户被实例化,然后 user 实例调用 save() 方法时,base class 中的以下行: return _this._ajaxService.send(options); 不起作用,因为 _ajaxService 未定义。

这是一个扩展基类用户类:

import {Base} from '../utils/base';

export class User extends Base {

  // properties
  id = null;
  email = null;
  password = null;
  first_name = null;
  last_name = null;

  constructor(source) {
    _super.CopyProperties(source, this);
  }
}

这是基类:

import {Component} from 'angular2/core';
import {AjaxService} from './ajax.service';

@Component({
  providers: [AjaxService]
})

export class Base {

  constructor(private _ajaxService: AjaxService) { }

  // methods
  public static CopyProperties(source:any, target:any):void {
    for(var prop in source){
      if(target[prop] !== undefined){
          target[prop] = source[prop];
      }
      else {
          console.error("Cannot set undefined property: " + prop);
      }
    }
  }

  save(options) {
    const _this = this;
    return Promise.resolve()
    .then(() => {
      const className = _this.constructor.name
                            .toLowerCase() + 's';
      const options = {
        data: JSON.stringify(_this),
        url: className,
        action: _this.id ? 'PATCH' : 'POST';
      };

      debugger;
      return _this._ajaxService.send(options);
    });
  }
}

除了 AjaxService 没有被注入(inject)基类之外,这工作正常。我想这是有道理的,因为用户正在被实例化而不是基础。

那么当 `Base 模块在另一个类上扩展时,我如何在 Base 模块 中使用 AjaxService

我想当我实例化用户时,调用了用户类中的构造函数,但没有调用注入(inject)服务的基类中的构造函数。

这是AjaxService:

   import {Injectable} from 'angular2/core';

@Injectable()

export class AjaxService {

  // methods
  send(options) {
    const endpoint = options.url || "";
    const action = options.action || "GET";
    const data = options.data || {};

    return new Promise((resolve,reject) => {
      debugger;
      $.ajax({
        url: 'http://localhost:3000' + endpoint,
        headers: {
          Authentication: "",
          Accept: "application/vnd.app.v1",
          "Content-Type": "application/json"
        },
        data: data,
        method: action
      })
      .done((response) => {
        debugger;
        return resolve(response);
      })
      .fail((err) => {
        debugger;
        return reject(err);
      });
    });

  }

}

最佳答案

可以在基础中注入(inject)服务,但无论如何您都必须从 User 类中传递它。您不能从 Base 继承服务的实际实例化,因此您必须将它从 User 传递给 Base。这不是 TypeScript 的限制,而是 DI 通常工作方式的一个特性。

像这样:

class User extends Base
  constructor(service: AjaxService) {
        super(service);
  }

如果 Base 为您实例化服务,您将无法影响 User 的实例化。这会抵消 DI 的很多好处,因为您会通过将依赖控制委托(delegate)给不同的组件来失去控制。

我知道你可能想通过在 Base 中指定它来减少代码重复,但这违背了 DI 的原则。

关于javascript - Angular2依赖注入(inject),类继承期间不注入(inject)服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34478353/

相关文章:

css - 跨元素共享 css 和 ts

java - 我将 jsp 中的值作为不同的值而不是我输入的值获取

javascript - AngularJS 2 中的 #num、[(ngModel)] ="num"和 [value] ="num"之间选择什么

javascript - 将CSS样式添加到java脚本中动态添加的<form>元素

javascript - 什么是更好的接口(interface)或类来拦截 Angular 6 中的 API 数据

angular - 如何在 Angular 2 Typescript 中复制到剪贴板?

http - Angular2 路由和拦截调用(HTTP API 中的某些地方从版本 2.1.0 更改为版本 2.2.3。)

node.js - typescript : Mongoose 模式的静态方法

javascript - 仅通过 Javascript 触发文件上传

javascript - 使用 Post 数据 (json) 重定向并具有 header