我已经在Angular7上开发了我的项目,现在我想探讨一下webAssembly。那么如何将最近的Web应用程序转换为WebAssembly?
答案 0 :(得分:1)
您可以按照以下步骤通过Web Assembly实施角度项目
您必须在角度项目中安装Web Assembly JavaScript API
npm install @types/webassembly-js-api --dev --save
现在使用C创建您的服务
#include <emscripten.h>
int EMSCRIPTEN_KEEPALIVE fibonacci(int n)
{
if (n == 0 || n == 1)
return n;
else
return (fibonacci(n - 1) + fibonacci(n - 2));
}
将C编译为Web Assembly(WASM)
emcc wasm/fibonacci.c -Os -s WASM=1 -s MODULARIZE=1 -o wasm/fibonacci.js
现在在Angular中创建服务
import { Injectable } from '@angular/core'
import { Observable, BehaviorSubject } from 'rxjs'
import { filter, map } from 'rxjs/operators'
import * as Module from './../../wasm/fibonacci.js'
import '!!file-loader?name=wasm/fibonacci.wasm!../../wasm/fibonacci.wasm'
@Injectable()
class WasmService {
module: any
wasmReady = new BehaviorSubject<boolean>(false)
constructor() {
this.instantiateWasm('wasm/fibonacci.wasm')
}
private async instantiateWasm(url: string) {
// fetch the wasm file
const wasmFile = await fetch(url)
// convert it into a binary array
const buffer = await wasmFile.arrayBuffer()
const binary = new Uint8Array(buffer)
// create module arguments
// including the wasm-file
const moduleArgs = {
wasmBinary: binary,
onRuntimeInitialized: () => {
this.wasmReady.next(true)
},
}
// instantiate the module
this.module = Module(moduleArgs)
}
public fibonacci(input: number): Observable<number> {
return this.wasmReady.pipe(filter(value => value === true)).pipe(
map(() => {
return this.module._fibonacci(input)
})
)
}
}
有关更多参考,您可以关注此博客https://malcoded.com/posts/web-assembly-angular/