Ionic 2 应用程序冲突 "Public" 与 "Public Static"

Ionic 2 App Conflict "Public" vs "Public Static"

我是这方面的业余爱好者,尝试编写应用程序代码,但我发现我的代码中存在冲突部分。我没有一个干净的代码只是让事情正常,我试过这样的:

    constructor(platform: Platform, public nativeStorage: NativeStorage) {
    platform.ready().then(() => {
    this.nativeStorage.getItem('NoTaleDB').then(function (json) {
    if (json) {
      GlobalVariables.novelList = JSON.parse(json);
    }
    });
    });
    }

    public static save() {
    this.nativeStorage.setItem('NoTaleDB', JSON.stringify(GlobalVariables.novelList)).then(() => {}, () => {});
}

并得到这个错误:

Property 'nativeStorage' does not exist on type 'typeof StorageService'

当我把函数修改成这样:

public save() {
    this.nativeStorage.setItem('NoTaleDB', JSON.stringify(GlobalVariables.novelList)).then(() => {}, () => {});
}

它找到了 nativeStorage,但我从 Pages 和服务本身得到了这个错误:

Property 'save' does not exist on type 'typeof StorageService'.

我已经尝试完成此应用很长时间了,但最终只是尝试修复错误。请提供一个简单的解决方案,新手可以理解的东西。谢谢。 <3

假设您希望函数 body 运行:

public static save() {
    this.nativeStorage.setItem('NoTaleDB', JSON.stringify(GlobalVariables.novelList)).then(() => {}, () => {})
}

this 可用于 static 成员,因为静态成员退出 class 而不是实例(this 引用的东西)。

固定代码

必须是:

public save() {
        this.nativeStorage.setItem('NoTaleDB', JSON.stringify(GlobalVariables.novelList)).then(() => {}, () => {})
    }

现在您 收到错误:

Property 'save' does not exist on type 'typeof StorageService'.

您正在呼叫 StorageService.save。这是错误的。您应该在一个实例上调用 save,例如

new StoargeService(pass in the stuff it needs).save(); // Works now

更多

关于 TypeScript 的一些文档 classes : https://basarat.gitbooks.io/typescript/content/docs/classes.html