However, when i run the project with the following import
import xml2js from 'xml2js';
then i get following error
node_modules/@types/xml2js/index"’ has no default export
So i then imported like this
import * as xml2js from 'xml2js';
I then created a service to use it and project compiles fine but service is undefined on runtime
Service Code
import { Injectable } from '@angular/core';
import * as xml2js from 'xml2js';
@Injectable({
providedIn: 'root'
})
export class DataTransformService {
constructor() {
}
public convertToJson(data: string): Object {
console.log(data);
console.log(xml2js);
console.log(xml2js.parseString);
let res;
// setting the explicitArray option prevents an array structure
// where every node/element is always wrapped inside an array
// set it to true, and see for yourself what changes
xml2js.parseString(data, { explicitArray: false }, (error, result) => {
if (error) {
throw new Error(error);
} else {
res = result;
}
});
console.log(res);
return res;
}
}
HomePage.ts where im using it but get undefined service
Thanks for your reply,
i actually did that, but i did it again just to be sure and got following message.
Looks like i need other dependcies to install but dont know how.
Can you please guide.
Thanks
Honestly I’m not sure, I think it’s probably because doing so you declare a new function to the loader which will end up being another instance and therefore won’t have access to the private injected service…but I’m tired so I won’t be surprise if I say something wrong
The short answer is “because JavaScript is poorly designed”. The longer answer is in here: arrow functions inherit this from their point of definition, whereas when you assign onFileResponse as an ordinary function, its execution context (what this means) is at the whim of the point of call.
@rapropos
Just to confirm,
to handle such cases where i access not TypeScript api (like FileLoader) ill have to/must use Arrow functions? there is no way i can pass this to that secondary function except calling that secondary function in arrow and passing it this manually?