简体   繁体   English

打字稿:无法从函数内部访问属性

[英]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 . var notificationOpenedCallback = function... ←在此函数中,我无法访问this.duyurular

I have to write this array ( duyurular ) up from json. 我必须从json编写此数组( duyurular )。 How can I do that? 我怎样才能做到这一点?

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. 至于构建数组,数据将作为JSON对象进入。 You need to get the data you want for your component out of the JSON and use it to build the array. 您需要从JSON中获取组件所需的数据,然后使用它来构建数组。 See this question for more advice on how to do that: How to convert JSON object to JavaScript array 有关如何执行此操作的更多建议,请参见此问题: 如何将JSON对象转换为JavaScript数组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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