[英]@input decorator instead of dependency injection service in Angular
据我了解,当从数据库或具有恒定值的类中获得持久数据时,我们应该使用依赖注入,因为我们可以在要实例化的类的构造函数中将服务作为参数发送。 该服务不需要实例化,也不需要作为参数传递,因为它知道从何处获取数据,并且要使用的类将在实例化时立即调用它。
但是,当信息不是永久性的也不是常量时,我们应该在子组件中使用@input装饰器,并使用父代的html模板传递参数值。
例如,假设我们有一个矩阵
@Component({
selector: 'app-matrix',
})
它具有行,列和行
export class MatrizComponent implements OnInit {
columnsQuantity:number;
rowsQuantity:number;
}
可以说这些行和列来自数据库或常量数据类,并且我们使用服务来获取该数据,以便我们可以使用获取服务的构造函数来扩展该类。
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和columnQuantity不是持久性或恒定性的,那么这种可注入服务不是可行的,那么我们是否总是必须在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>
这是否总是正确的,或者即使对于非持久性或恒定数据,我也应该尝试使用依赖项注入吗? 如果我应该这样做,该怎么办?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.