3

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.

CKE
  • 1,533
  • 19
  • 18
  • 29
  • check this : https://stackoverflow.com/questions/40635259/call-pure-javascript-function-from-angular-2-component – Chellappan வ Jul 19 '18 at 04:24
  • The problem is with the statement parsedJsonResponse = JSON.parse(this.jsonResponse); Why are you using this over here? – Avij Jul 19 '18 at 04:47
  • @Avij I am using this to parse response. The console.log in that function also returns the response. –  Jul 19 '18 at 05:22

2 Answers2

0

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

Azamat Zorkanov
  • 779
  • 1
  • 4
  • 9
  • I did this and now it gives Uncaught TypeError: Cannot read property of 'content' of undefined at dataCall() and getData() –  Jul 19 '18 at 15:55
0

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.

Lasithe
  • 1,916
  • 1
  • 15
  • 20
  • I have made these changes. now it gives `Uncaught TypeError: Cannot read property of 'content' of undefined` at `dataCall()` and `getData()`. –  Jul 19 '18 at 06:03