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

Oms*_*msl 2 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();
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

var notificationOpenedCallback = function...←在这个功能里面,我无法访问this.duyurular.

我必须duyurular从json 编写这个数组().我怎样才能做到这一点?

Chr*_*arp 6

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

    var notificationOpenedCallback = function(jsonData) {
      this.duyurular = jsonData.notification.payload;
    };
Run Code Online (Sandbox Code Playgroud)

将其更改为胖箭头函数或定义此块之外的范围:

首选方案:

    var notificationOpenedCallback = (jsonData) =>  {
      this.duyurular = jsonData.notification.payload;
    };  
Run Code Online (Sandbox Code Playgroud)

在功能选项之外:

    const self = this;

    var notificationOpenedCallback = function(jsonData) {
      self.duyurular = jsonData.notification.payload;
    };     
Run Code Online (Sandbox Code Playgroud)

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