Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: Cannot access property from inside a function

export class DuyurularPage {
    duyurular: any;
    loading: any;

    constructor(public navCtrl: NavController, public navParams: NavParams, public loadingPage: LoadingController,
        platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {

        this.loading = this.loadingPage.create({
            content: `
            <ion-spinner></ion-spinner>`
        });

        platform.ready().then(() => {
            statusBar.styleDefault();
            splashScreen.hide();

            var notificationOpenedCallback = function (jsonData) {
                this.duyurular = jsonData.notification.payload;
            };

            alert
            window["plugins"].OneSignal
            .startInit("12312412412412", "1231241212")
            .handleNotificationOpened(notificationOpenedCallback)
            .endInit();
        });
    }
}

var notificationOpenedCallback = function... ← Inside this function, I cannot access this.duyurular.

I have to write this array (duyurular) up from json. How can I do that?

like image 848
Omsl Avatar asked Nov 03 '17 11:11

Omsl


1 Answers

It's because this function below has the wrong scope.

    var notificationOpenedCallback = function(jsonData) {
      this.duyurular = jsonData.notification.payload;
    };

Change it to a fat arrow function or define the scope outside of this block:

Preferred option:

    var notificationOpenedCallback = (jsonData) =>  {
      this.duyurular = jsonData.notification.payload;
    };  

Outside the function option:

    const self = this;

    var notificationOpenedCallback = function(jsonData) {
      self.duyurular = jsonData.notification.payload;
    };     

As for building the array, the data will come in as a JSON object. You need to get the data you want for your component out of the JSON and use it to build the array. See this question for more advice on how to do that: How to convert JSON object to JavaScript array

like image 64
Chris Sharp Avatar answered Nov 19 '22 00:11

Chris Sharp