2

I have a method that returns an Observable as follows:

public myMethod(params): Observable<CertainType> {
    // some code goes here;
    return defer(() => this.customHttp.request<XML>(config, ctx)).pipe(
    map(
            (xmlRes: string) => {
                const xmlHandler = new strongsoap.soap.XMLHandler();
                const rawSFResponse = xmlHandler.xmlToJson(null, xml, null);
                const res = rawSFResponse["Body"]["SFResponse"]["SFResult"];
                // more code goes here;
            }
        )
    )
}

The problem with this piece of code is that I receive an error in the console that says Cannot read property 'SFResult' of undefined. And if I try console-logging the rawSFResponse object it gets printed out but when I click on it it says "value below was evaluated just now".

As far as I understand it happens because this statement res = rawSFResponse["Body"]["SFResponse"]["SFResult"]; is executed before the res object is fully formed, namely at the moment it gets executed the content of the SFResult field is still undefined. Is it correct? If so, then what would be the best way to wait for it to be formed. Maybe I have to wrap the parsing function into a promise and then use await on it?

Albert
  • 2,146
  • 10
  • 32
  • 54
  • I guess this is more like a soap xml handling issue. If the parsing happens asynchronously, the question is how can you wait for the result to be fully parsed. I don't know that library, but is there a possibility to get the result through callback you pass to the parser or as a promise from the parser? – Wilt Mar 01 '20 at 18:08
  • @Wilt With this lib it should not happen asynchronously, i don't know how else to explain the source of the 'value below was evaluated just now' error. There's another custom parsing function here, and it returns a Promise but it's hard to use it inside the construction I've chosen. Maybe that behavior is because I convert a Promise into an Observable? I've just run out of ideas. – Albert Mar 01 '20 at 18:26
  • The message you get is nicely explained [here](https://stackoverflow.com/a/57843750/1697459). It does suggest the object has changed, so I suspect something asynchronous going on. But try once to do `console.log(JSON.parse(JSON.stringify(rawSFResponse));` then you get a snapshot of the object in console before it changed. – Wilt Mar 01 '20 at 20:40

0 Answers0