【问题标题】:Typescript: Cannot access property from inside a function打字稿:无法从函数内部访问属性
【发布时间】:2018-04-16 03:44:04
【问题描述】:
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)。我该怎么做?

【问题讨论】:

    标签: javascript json typescript


    【解决方案1】:

    这是因为下面这个函数的作用域不对。

        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

    【讨论】:

    • 非常非常感谢 :) 但是我还有一个问题。
    • 我照你说的做了,我可以alert()传入数据,但是进不了html页面。

      {{item.title}}

      {{item.body}}
    • 数据将以 JSON 对象的形式传入。您需要从 JSON 中获取组件所需的数据并使用它来构建数组。有关如何执行此操作的更多建议,请参阅此问题:stackoverflow.com/questions/14528385/…
    • 非常感谢
    猜你喜欢
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    • 2011-03-13
    • 2021-12-08
    • 2016-04-16
    • 2018-09-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多