如何在javascript中使用角度2+进行服务

问题描述 投票:1回答:4

我有以下场景。

我有一个简单的角度2应用程序与服务,我添加到app.module中的提供程序。当我点击一个按钮时,应用程序应该加载一个javascript文件并执行一个函数,例如在这个javascript文件中定义的函数A.所以问题是如何在这个函数A中访问服务。我的考虑是将服务附加到全局窗口变量。有没有更好的方法来实现它?

码:

export class MyService{
    public editProjectDone = new Subject<string>();
}

app.module.ts
{
    ...providers: [MyService]
}

app.component.html
<button (click)="editProject()">Edit project</button>

app.component.ts
function editProject(){
    ... load Javascript file
    call javascript file
    js.editProject("projectId") // call function defined in javascript file
}

javascript file
{
    function editProject(projectId)
    {
        //do calculation 
        // fire event that calculation is done
        // the calcuation is not done in typescript, but here
        MyService.editProjectDone.next() 
        // The question is here how to access the event and fire it
    }
}
javascript angular
4个回答
3
投票

所以你想在javascript函数A()中访问角度服务方法。

例如:

您的服务类:

export class SettingsService{
    getLanguage() {
        return 'en-GB';
    }
}

你的javascript文件

function A() {
    settingsService.getLanguage();
}

解决方案:自定义事件

基本上你在javascript文件中定义一个自定义事件处理程序。并定义自定义事件并在Angular单击事件函数中调度自定义事件。

app.component.html:

<input type="button" value='log' (click)="logclick($event)">

app.component.ts

constructor(private settings: SettingsService){}

logclick(event){
    // define custom event
    var customevent = new CustomEvent(
    "newMessage", 
    {
        detail: {
            message: "Hello World!",
            time: new Date(),
            myservice: this.settings //passing SettingsService reference
        },
        bubbles: true,
        cancelable: true
      }
    );
    event.target.dispatchEvent(customevent); //dispatch custom event
}

javascript文件:

// event handler function
function newMessageHandler(e) {
    console.log(
        "Event subscriber on "+e.currentTarget.nodeName+", "
        +e.detail.time.toLocaleString()+": "+e.detail.message
    );
    //calling SettingsService.getLanguage()
    console.log(e.detail.myservice.getLanguage());
}
//adding listener to custom event.
document.addEventListener("newMessage", newMessageHandler, false);

示例输出:

Event subscriber on #document, 9/11/2018, 11:31:36 AM: Hello World!
en-GB

注意:我没有添加动态加载javascript文件的部分。我假设您已经能够从您的评论中做到这一点。


1
投票

使用window对象以适当的方式将变量声明为public。只导出一些功能而不是整个服务,并以某种标准方式导出如下。

在Angular

export class AbcService {
  constructor() {
    const exportFunctions = {
      xyzFunction: this.xyzFunction.bind(this),
      pqrFunction: this.pqrFunction.bind(this)
    }; // must use .bind(this)
    window['ngLib']['abcService'] = exportFunctions;
  }

  xyzFunction(param1, param2) {
    // code
  }

  pqrFunction() {
    // code
  }

  private oneFunction() {
    // code
  }

  private twoFunction() {
    // code
  }
}

在Javascript中

ngLib.abcService.xyzFunction(value1, value2);
ngLib.abcService.pqrFunction();

0
投票

您必须使用服务变量来访问特定服务的函数和变量。

在这里,我演示了如何做到这一点。

export class AppComponent  {
  name = 'Angular';
  constructor(private myServices: MyServices){
     this.myServices.sayHello();
  }
}

整个代码在这里:https://stackblitz.com/edit/angular-services-example


0
投票

首先,您需要在调用服务之前导入js文件,这可以通过以下方式完成:

TS

let js: any = require('JSFileNAME')['default']; //Something lik this in constructer

然后一旦导入文件,你需要在你的Ts中创建一个js的实例化

this.newObjectOfJs = new js(); // pass any paramater if its required.

此后,您将能够从JSfile访问方法和服务。

© www.soinside.com 2019 - 2024. All rights reserved.