简体   繁体   English

内部服务中的角负载外部类

[英]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装饰器。

Stackblitz demo Stackblitz演示

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

相关问题 如何在 div 中加载外部 Angular 应用程序? - How to load an external Angular app inside a div? 在Angular 2中加载外部脚本 - Load external scripts in Angular 2 Angular:访问组件模板内部的外部静态类 - Angular: Access an external static class inside of a components template 如何从Typescript / Angular 5中的服务加载类的属性? - How to load an property of a class from a service in Typescript/Angular 5? 如何使用构造函数内部的参数测试angular2类/服务? - How to test angular2 class/service with parameters inside constructor? Angular2从调用服务的构造函数中的类访问@Input - Angular2 access @Input from class inside constructor that calls a service Angular Service / Factory-Cordova文件传输内部的类属性未更新 - Angular service/factory - class property not updating inside the cordova file transfer 如何在 Angular 组件的服务类中调用函数 - How to call a function inside service class in a component in Angular 如何在类中使用Angular创建服务实例(可注入) - How can I create an instance of a service (injectable) with Angular inside a class 在Angular Routing Module类中运行服务功能 - Run a Service Function inside an Angular Routing Module class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM