[英]Angular load external class inside service
I am trying to load a external typescript class inside my angular service. 我正在尝试在我的角度服务内部加载一个外部打字稿类。 I have a service called anyservice.
我有一项名为anyservice的服务。 And I am creating a export class inside one folder and I want to get one function inside my service for that my code for class is:
我正在一个文件夹中创建一个导出类,我想在我的服务中获得一个函数,因为我的类代码是:
export class Functions {
testy() {
alert("I am testy");
}
}
I am calling this Functions class inside my service using: 我在服务内部使用以下方法调用此Functions类:
import{Functions} from '../data/f'
But inside my service when I am trying to get this using: 但是在我的服务内部,当我尝试使用以下方法时:
constructor(private f: Functions)
I am getting error: 我收到错误消息:
ERROR Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[Functions]:
StaticInjectorError(Platform: core)[Functions]: StaticInjectorError(平台:核心)[功能]:
How can I call my function inside my service like this: 如何在服务中这样调用函数:
test() {
this.f.testy();
}
What is the best possible way to access external class inside services 什么是访问服务内部类的最佳方法
It's better if you can add the Injectable
decorator to your class. 最好将
Injectable
装饰器添加到您的类中。 However, if you can't (maybe it's a classs from a 3rd party library), you can still inject it in your components/services as long as you declare it in the module's providers 但是,如果您不能这样做(也许这是来自第三方库的类),只要您在模块的提供程序中声明它,就仍然可以将其注入到组件/服务中。
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent, HelloComponent ],
bootstrap: [ AppComponent ],
providers: [Functions]
})
Note : The Injectable
decorator would be required on your Functions
class if that class required some other class to be injected in its own constructor. 注意 :如果
Functions
类需要将其他一些类注入其自己的构造Functions
,则该类需要Injectable
装饰器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.