【发布时间】:2019-11-29 21:49:09
【问题描述】:
我有一个具有以下场景的 Angular 应用程序,尽管我相信这个场景也适用于其他框架/场景:
public export class FooComponent {
private userId: number;
constructor(private readonly authService: AuthService) { }
ngOnInit() {
this.userId = authService.GetUser().id;
this.getDataByUserId(this.userId);
}
private getDataByUserId(userId: number) {
// Load data using the param
}
public anotherFunction(fooId: number) {
// Gets called by an event occurring or something
// Perform an API Call
// Now reload the data by using the private state variable.
this.getDataByUserId(this.userId);
}
}
getDataByUserId(userId: number)应该使用参数来接收userId,还是应该无参数只访问组件的private userId?
在我看来,将变量作为参数传递的优缺点如下:
专业人士
- 更容易的单元测试;如果组件有点大,你可能不需要以特定的方式设置组件来工作,你只需要传递一个数字
- 如果您的组件的许多功能访问该变量并对其进行更改,您可能会遇到该变量处于无效状态的情况。
骗局
- 如果您不再以特定方式设置组件,因为您可以将值作为参数传递,则测试期间组件的“状态”可能无法反映生产场景期间的预期状态。由于您的测试不能反映真实的工作条件,因此它们可能被认为是易碎的。
- 如果你传递了错误的值,事情将会/可能会出错。
这里什么被认为是更好的选择?在哪里划清界限?
谢谢!
【问题讨论】:
标签: angular architecture