登录
首页 >  Golang >  Go问答

在 Angular 服务中正确集成 WASM 的方法

来源:stackoverflow

时间:2024-02-25 08:18:25 196浏览 收藏

对于一个Golang开发者来说,牢固扎实的基础是十分重要的,golang学习网就来带大家一点点的掌握基础知识点。今天本篇文章带大家了解《在 Angular 服务中正确集成 WASM 的方法》,主要介绍了,希望对大家的知识积累有所帮助,快点收藏起来吧,否则需要时就找不到了!

问题内容

我将一些 wasm 代码(从 go 代码编译而来)集成到 angular 中以使用一些功能。目前,这仅在一个地方完成,因此不会在整个应用程序中共享。我只是使用了 wasm 和 go 的“标准”程序:

let go = new Go();

WebAssembly.instantiateStreaming(fetch('mywasm.wasm'), go.importObject).then((res) => {
  go.run(res.instance);

  myCoolWasmFunction();
});

但是,我想在应用程序的多个部分执行 wasm,因此尝试将其移至服务中。我能够使用 rxjs 主题并在 go.run(...) 之后监听该函数中的“执行请求”,但我无法将任何内容返回到应用程序的其他部分。

基本上,我正在寻找一种干净且可用的方法来执行 angular 应用程序中 wasm 公开的不同功能。我是否应该将 wasm 内容放入 index.html 并创建一个仅调用这些“全局可用”函数的服务?我如何使 angular 能够仅使用 .d.ts 文件来识别这些?


解决方案


我在 this Github Repo 的帮助下解决了这个问题。它就像在服务内创建一个公共变量一样简单,然后在加载 wasm 时,将导出的 wasm 函数设置为该变量,以便可以从服务外部调用它们。对于以下示例,我添加了一个小型打字稿接口以使其能够实现类型安全:

因此,在 wasm 服务中可能如下所示:

private Suite: WasmSuite; // Here the exported functions are stored after wasm was initiated
/*
 WasmSuite is defined like this:
 type MyFunctionInterface = (input: string) => string;

 interface WasmSuite {
     myFunction: MyFunctionInterface;
 }
*/

// This is just to let components know when WASM is ready
public ready: BehaviorSubject = new BehaviorSubject(false);

constructor() {
  // Init wasm, then update the ready state
  this.init().then(_ => {      
    this.ready.next(true);
  });
}

private async init() {
  let go = new Go();

  return WebAssembly.instantiateStreaming(
    fetch('assets/main.wasm'),
    go.importObject
  ).then((res) => {
    go.run(res.instance);

    // Set the Suite to an object containing the functions. The casting of the function is somewhat optional, but I think it's good practice.
    this.Suite = {
      myFunction: my_exported_func as MyFunctionInterface,
      // "my_exported_func" is what I exported in Go via js.Global().Set("my_exported_func", js.FuncOf(myGoFunc))
    };
  });
}

public callMyFunction(input: string) {
  // I like to publish methods to components instead of the suite object, so this is just an "interface" between callers and WASM.
  return this.Suite.myFunction(input);
}

好了,本文到此结束,带大家了解了《在 Angular 服务中正确集成 WASM 的方法》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>