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

时间:2017-11-03 11:58:50

标签: javascript json typescript

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...←在此功能中,我无法访问this.duyurular

我必须从json编写这个数组(duyurular)。我怎么能这样做?

1 个答案:

答案 0 :(得分:5)

这是因为下面这个函数的范围是错误的。

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

将其更改为胖箭头功能或在此块之外定义范围:

首选项:

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

在功能选项之外:

    const self = this;

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

对于构建数组,数据将作为JSON对象进入。您需要从JSON中获取组件所需的数据,并使用它来构建阵列。有关如何执行此操作的更多建议,请参阅此问题:How to convert JSON object to JavaScript array