@input装饰器而不是Angular

时间:2017-10-19 19:36:27

标签: angular dependency-injection angular2-template angularjs-decorator

据我所知,当存在来自数据库或具有常量值的类的持久数据时,我们应该使用依赖注入,因为我们可以将服务作为参数发送到我们要去的类的构造函数中实例化。该服务不需要实例化,也不作为参数传递,因为它知道从哪里获取数据,并且将要使用的类只是在实例化时调用它。

但是当信息不是持久的既不是常量时,我​​们应该在子组件中使用@input装饰器,并使用父级的html模板传递参数值。

例如,假设我们有一个矩阵

    @Component({
        selector: 'app-matrix',
      })

它有行,列和行

export class MatrizComponent implements OnInit {
  columnsQuantity:number;
  rowsQuantity:number;
}

假设这些行和列来自Database或Constant数据类,我们使用服务来获取该数据,以便我们可以使用获取服务的构造函数扩展该类

export class MatrixComponent implements OnInit {
  columnsQuantity:number;
  rowsQuantity:number;
  constructor(private service:MatrixService) { 

  }
}
ngOnInit() {
    this.columnsQuantity = this.service.getColumnsQuantity();
    this.rowsQuantity = this.service.getRowsQuantity();
}

当我们需要实例化这个MatrixComponent时,我们只需编写

<app-matrix></app-matrix>

在父类的HTML模板中。这是因为会有像这样的服务

import { Injectable } from '@angular/core';
@Injectable()
export class MatrixService {
  private columnsQuantity: number;
  private rowsQuantity:number;
  constructor(private service:SessionInfoService) {
        this.columnsQuantity = getColumnsQuantityFromDataBaseOrConstantClass();
        this.rowsQuantity = getRowsQuantityFromDataBaseOrConstantClass();
 }
  getColumnsQuantity() {
      return this.columnsQuantity;
  }
  getRowsQuantity() {
    return this.rowsQuantity;
  }
}

服务和依赖注入是有意义的,因为有一种方法可以从数据库获取持久数据或者注入服务可以访问的常量值。

在上面的代码中,rowsQuantity和ColumnsQuantity是持久的或常量的。

但是,如果rowsQuantity和columnsQuantity不持久或不变,那么这个可注射服务是不可能的,那么我们是否总是必须在MatrixComponent中使用@input装饰器?

在这种情况下,我们不必在构造函数中使用服务,而是使用@input装饰器,如下所示:

export class MatrixComponent implements OnInit {
      @input() columnsQuantity:number;
      @input() rowsQuantity:number;
      constructor() { 

      }
    }
    ngOnInit() {


    }

当我们需要实例化这个MatrixComponent时,我们必须传递参数

<app-matrix [columnsQuantity]="whateverColumnsValueHasBeenJustGottenAndIsNotPossibleToInject" [rowsQuantity] = "whateverRowssValueHasBeenJustGottenAndIsNotPossibleToInject"></app-matrix>

这是否总是正确或者我应该尝试使用依赖注入,即使是非持久性或常量数据?在我应该的情况下,我该怎么做?

0 个答案:

没有答案