I am using angular, trying to pass an object to the web worker for the background process. the class is
Article{
method1();
propertyA;
}
addEventListener('message', ({ data }) => {
// if without plainToClass, how to call article.method1()
data.article=plainToClass(Article, data.article);
console.log(data.article.method1());
});
Because in the web worker thread, I want to use article.method1(),
After the object is passed to web worker, it becomes an object that does not have methods but only properties. Why is this? pass as a string?
Tried to use plainToClass()
to convert the passed obj to an Object with method, which in main thread I am able to do so, load string and convert to Class object. but in web worker, it complains about Reflect.getMetadata is not a function
. Which seems it cannot find the imported import 'reflect-metadata'
in polyfills.ts
Answer:
It turns out I need to import this in Article class file
import 'reflect-metadata';
export class Article implements Clonable{
}
Passing data to a Web worker is done by serializing the object , so you won't be able to pass in behavior. Instead, you'll need to either use plainToClass
as you have in your example, or you can provide the functionality in a helper function.
Additionally, import reflect-metadata
is an import for side-effects. This code is run once per context , so it will need to be run again inside the worker , and then plainToClass
should work.
That said, a simpler approach might be to try to call the class constructor using the values passed in - if that's possible?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.