简体   繁体   中英

Reference error when calling javascript function in angular 5

I am trying to call one of the function in from .js file in angular whenever a route change happen.

This is my code in the javascript file and I need to call need to call the appData function in angular.

The console.logs for console.log(parsedJsonResponse); and console.log(appData) works fine and I am getting the JSON response.

window.dataLayer = (function () {

  var dataCall = function () {
    return new Promise((resolve, reject) => {

      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function () {
        if (this.readyState == 4) {
          if (this.status == 200) {
            resolve(this.responseText);
          } else {
            console.log(this.status + '.....' + this.statusText)
          }
        }
      };

      xhttp.open("GET", "http://localhost:4200/assets/sample.json", true);
      xhttp.send();
    })

  }

  dataCall().then((CallResponse) => {
    getData(CallResponse)

  });

  window.addEventListener("load", function (event) {
    appData();
  })

  var getData = function (cData) {
    jsonResponse = cData.replace(/'/g, '"');
    parsedJsonResponse = JSON.parse(this.jsonResponse);
    var appData = parsedJsonResponse['content']['copy$$' + applicationContent];

    console.log(parsedJsonResponse);
  }

I am calling appData function in

  var appData = function (applicationContent) {
    var appData = parsedJsonResponse['content']['copy$$' + applicationContent];
    console.log(appData)
  }

  return {
    appData: appData,
    dataCall: dataCall

  }

}())

This is my code in angular calling the function.

When calling this function in angular I'm getting ReferenceError: parsedJsonResponse is not defined .

constructor(private router:Router) {}

 ngOnInit(){
  this.router.events
  .filter(event => event instanceof NavigationStart)
  .subscribe((event: NavigationStart) => {
    dataLayer.appData();
   })

 };

What is going wrong? Thanks.

Try to declare parsedJsonResponse variable inside of a dataLayer function:

window.dataLayer = (function () {
   var parsedJsonResponse;
   /* rest of your code */

EDIT

The problem why this is happening, because your variable parsedJsonResponse gets its value, when ajax response comes from the server. It means, that it depends on async action. What you can do, is wait for response in promise. My suggestion is to keep that promise in new variable getAsyncData :

var getAsyncData = dataCall().then((CallResponse) => {
  getData(CallResponse)
});

also don't forget to add that variable into return object:

return {
  appData: appData,
  dataCall: dataCall,
  getAsyncData: getAsyncData
}

and you can use it in your angular app like so:

dataLayer.getAsyncData.then(() => {
 dataLayer.appData();
});

One more thing I've noticed, that you are using applicationContent in getData function, but it haven't been initialized in your function dataLayer. The only usage on that variable in appData:

var appData = function (applicationContent) {

You should consider also initializing that variable on top of your function.

window.dataLayer = (function() {
   var parsedJsonResponse;
   var applicationContent;
   /* rest of your code */

Here is the code, which I've made on top of your's with slight changes(here I sending response to jsonplaceholder server, so parsing that response is different, and also I've removed load event listener:

https://jsbin.com/birofufade/edit?html,js,console,output

parsedJsonResponse variable should be declared outside all functions if you're going to use it in different functions. Otherwise parsedJsonResponse is private to getData function.

window.dataLayer = (function () {
   var parsedJsonResponse;
   // ...rest

Next you need to remove the function call inside window load event. appData() is getting called in window load but the data is still fetching and parsedJsonResponse has no content.

window.addEventListener("load", function (event) {
    // appData();
})

In getData function remove this since jsonResponse is a private variable.

 parsedJsonResponse = JSON.parse(jsonResponse);

I hope this will help.

EDIT: Anyway I don't encourage using external js files. Try to use a service inside your Angular app.

UPDATE: You are not passing the parameter in dataLayer.appData() . You are not handling the exceptions properly in the API request.

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