简体   繁体   English

如何在 Angular/Typescript 中隔离私有静态函数?

[英]How to isolate private static functions in Angular / Typescript?

How to isolate private static functions of a class into another file.如何将一个类的private static functions隔离到另一个文件中。

In my component.ts I have lot of static functions and need to put them in another ts file for better readability purposes.在我的component.ts我有很多静态函数,需要将它们放在另一个 ts 文件中以提高可读性。 How can I do that ?我怎样才能做到这一点 ?

Like we can put interfaces in another file and export them is there something similar for static functions too ?就像我们可以将接口放在另一个文件中并导出它们一样,静态函数也有类似的东西吗?

Desired Result is I am able to call Component.foo() in component.ts file, but private static foo() exists in logic.ts file .期望的结果是我能够在component.ts文件中调用Component.foo() ,但在logic.ts文件中存在private static foo() Is it possible to do so ?有可能这样做吗?

You can't do what you're asking.你不能做你所要求的。

You can easily create an external class for static files like:您可以轻松地为静态文件创建一个外部类,例如:

export class Logic {
    public static foo() {
        console.log('foo');
    }
}

And then in component.ts you can call Logic.foo() just fine.然后在component.ts你可以调用 Logic.foo() 就好了。 However, you can't make foo private because then it's not available in Component.但是,您不能将 foo 设为private因为它在 Component 中不可用。 Also, while you rename Logic inside component or wherever else, ie此外,当您在组件内部或其他任何地方重命名Logic ,即

const LogicalFunctions = Logic;
LogicalFunctions.foo();

you can't reference them as a part of Component, a la Component.foo() .你不能将它们作为 Component 的一部分引用,比如Component.foo()

It depends on what exactly you want to achieve.这取决于您究竟想要达到什么目的。

You can have a file logic.ts:你可以有一个文件 logic.ts:

export function foo(){ }

And then in your Component-class import this into a private static property if you don't mind an extra step in calling your functions.然后在你的组件类中,如果你不介意在调用你的函数时有一个额外的步骤,那么将它导入一个私有的静态属性。

import * as Logic from './Logic'

class Component
{
    private static Logic = Logic; 

    public DoStuff() {
        Component.Logic.foo();
    }
}


Component.Logic.foo(); // Not allowed

Of course anyone could reuse Logic.ts, but if your aim with "private" just is to limit the API of Component , it might be an idea.当然,任何人都可以重用 Logic.ts,但是如果您的“私有”目的只是限制Component的 API,那么这可能是一个想法。

And of course your foo won't have access to other private statics of Component, but if you need that I don't see the point in trying to separate your class into multiple files.当然,您的foo将无法访问 Component 的其他私有静态信息,但是如果您需要这样做,我认为尝试将您的类分成多个文件没有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM