Search code examples
javascripttypescriptionic-frameworkionic2ionic-native

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


I'm an amateur to this thing, tryin' to code an app and I found conflictin' parts on my code. I don't have a clean code just makin' things work, I tried it out like this:

    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(() => {}, () => {});
}

And got this error:

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

When I modify the function into this:

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

It finds the nativeStorage but I get this error instead from Pages and the service itself:

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

I've been tryin' to finish this app for a long time now but ends up only tryin' to fix bugs. Please, provide a simple solution, something a newbie can understand. Thanks. <3


Solution

  • Assuming that you want the function body for this to function:

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

    this is not available for static member as static members exit on the class and not the instance (the thing referenced by this).

    Fixed code

    Has to be :

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

    Now you are getting the error:

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

    You are calling StorageService.save. This is wrong. You should be calling save on an instance e.g.

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

    More

    Some docs on TypeScript classes : https://basarat.gitbooks.io/typescript/content/docs/classes.html