Ionic 3 中的全局函数
Global function in Ionic 3
我想创建一个名为 "translate" 的全局函数。据我所知,我可以在 app.module.ts 文件中定义全局变量及其值。所以我尝试了以下代码:
export function translate(string) {
// i am not sure if it would make a difference if i would use var
let ts = new TranslateService();
return ts.get(string).subscribe(res=>{
return res;
});
}
所以也许我尝试使用错误的 class,也许错误在其他地方。我使用 ngx-translate Module (and it works great). Instead of always declaring to use the "TranslateService" (in every class where a translation is needed), i want to have a global function, where i can access the translations via only a function (i do not want to call another class...). You can see the code that i do like to use in the global function at the very end of the link (ngx-translate)
提前致谢。
global 对我来说意味着在项目的任何地方都可以访问某些东西。
我认为这是一个非常糟糕的主意,即使 如果 你通过一些乱七八糟的 hack 以某种方式让它工作,这也不是它的预期工作方式。
TranslateService
已经是一项服务,您可以在需要的每个 class 中注入它。使用 Angulars 依赖注入来注入服务是使用它的预期方式。如果您担心最终会有多个翻译服务 - 别担心,Angulars 依赖注入系统会解决这个问题。
我猜你想这样做是因为你总是必须在你的构造函数中写 public translate: TranslateService
。但是,如果您在 app.module 中导出一个函数,则必须在 class 中再次导入它,因此您每次都必须编写 import { translate } from 'path/to/app.module/translate';
。
我想创建一个名为 "translate" 的全局函数。据我所知,我可以在 app.module.ts 文件中定义全局变量及其值。所以我尝试了以下代码:
export function translate(string) {
// i am not sure if it would make a difference if i would use var
let ts = new TranslateService();
return ts.get(string).subscribe(res=>{
return res;
});
}
所以也许我尝试使用错误的 class,也许错误在其他地方。我使用 ngx-translate Module (and it works great). Instead of always declaring to use the "TranslateService" (in every class where a translation is needed), i want to have a global function, where i can access the translations via only a function (i do not want to call another class...). You can see the code that i do like to use in the global function at the very end of the link (ngx-translate)
提前致谢。
global 对我来说意味着在项目的任何地方都可以访问某些东西。
我认为这是一个非常糟糕的主意,即使 如果 你通过一些乱七八糟的 hack 以某种方式让它工作,这也不是它的预期工作方式。
TranslateService
已经是一项服务,您可以在需要的每个 class 中注入它。使用 Angulars 依赖注入来注入服务是使用它的预期方式。如果您担心最终会有多个翻译服务 - 别担心,Angulars 依赖注入系统会解决这个问题。
我猜你想这样做是因为你总是必须在你的构造函数中写 public translate: TranslateService
。但是,如果您在 app.module 中导出一个函数,则必须在 class 中再次导入它,因此您每次都必须编写 import { translate } from 'path/to/app.module/translate';
。