简体   繁体   中英

JavaScript function in external HTML file not invoked when an object is passed as parameter from an Angular2 component

I am using Angular2 for a mobile app and I have to open a URL in a new window using one of the inbuilt cordova plugins (InAppBrowser). To detect the event upon which the page-loading of the new window completes, there is an EventListener "loadstop" as given below. This is from a component inside my app

var options = {url: "mylink", fileName: "myfilename"};    
let browser = new InAppBrowser('http://www.myexamplesite.com', '_blank', 'location=no');
browser.on("loadstop")
      .subscribe(
      () => {
        browser.executeScript(
          {
            code: "getOptions("+options+");"
          });
      },
      err => {
        console.log("Loadstop Event Error: " + err);
      });

The external URL is a HTML file with some JavaScript code. The getOptions(options) is a JavaScript function defined there as inline. This is the function:

function getOptions(options) {
     alert("Values are "+options['url']+" and "+options['name']);
}

But the function is not invoked in this way. It works when I remove the parameter options from both the call and the definition. What could be the reason? Are the objects in Angular2 and JavaScript not interoperable?

The problem is the way you are concatenating the string and options . You could use JSON.stringify to get something you can concatenate.

Illustration of the issue:

var options = {url: "mylink", fileName: "myfilename"};   


// This is what you do:
console.log("getOptions("+options+");");

// This is what you should do:
console.log("getOptions(" + JSON.stringify(options) + ");");

//
// This shows it works: `getOptions` will be called.
//
function getOptions(options) {
    console.log("OPTIONS: ", options);
    console.log("Values are "+options['url']+" and "+options['fileName']);    
}

eval("getOptions(" + JSON.stringify(options) + ");");

If you run the above, you get this on the console:

getOptions([object Object]);
getOptions({"url":"mylink","fileName":"myfilename"});
OPTIONS:  { url: 'mylink', fileName: 'myfilename' }
Values are mylink and myfilename

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM