Angular 我应该将带有参数的私有状态传递给函数,还是函数应该使用私有状态?

Angular 我应该将带有参数的私有状态传递给函数,还是函数应该使用私有状态?,angular,architecture,Angular,Architecture,我有一个Angular应用程序,具有以下场景,尽管我相信此场景也适用于其他框架/场景: public export class FooComponent { private userId: number; constructor(private readonly authService: AuthService) { } ngOnInit() { this.userId = authService.GetUser().id; this

我有一个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,还是应该是无参数的,只访问组件的
私有userId

在我看来,将变量作为参数传递的利弊如下:

专业版
-更容易的单元测试;如果组件稍微大一点,您可能不需要以特定的方式设置组件来工作,您只需要传递一个数字 -如果组件的多个函数访问该变量并对其进行更改,则可能会出现该变量处于无效状态的场景

Con的
-若您不再以特定的方式设置组件,因为您可以将该值作为参数传递,那个么测试期间组件的“状态”可能不会反映生产场景期间的预期状态。由于您的测试不能反映实际工作条件,因此可能会被视为脆性测试。 -如果你传递了错误的值,事情就会/可能会出错

这里什么被认为是更好的选择?一个人的底线在哪里


谢谢

我认为这取决于
getuserdatabyd
函数的真正用途

是否总是使用存储在组件状态中的
userId
调用它(因此它是某种
currentUserId
)?然后,最好创建一个不带参数的
getCurrentUserData
方法,该方法将始终从状态中获取用户ID并进行测试

如果您使用不同的用户ID源在组件或应用程序的不同部分重用它,那么将其作为一个单独的函数并在组件状态下不依赖它进行测试似乎是合乎逻辑的。然后,当您测试另一个函数时,您应该在需要时模拟
getUserDataById