2

How do you all save data to a service using TypeScript?

If I have a service like this:

class MyService {
    persistentData: Object;

    constructor() {
        this.init();
    }

    private init = (): void => {
        this.persistentData = {};
    }

    public saveData = (data): Object {
        this.persistentData = data;
    }
}

How would I go about keeping the data consistent through different routes? Each time a new route is called, the service class is instantiated again, and the persistentData object is reset to be blank. Normally in regular JavaScript you could do:

angular
    .factory('myFactory', function() {
        var persistentData = {};

        return {
            setFormData: function(newData) {
                persistentData = newData;
            }
        }
    })

And this works. I must be missing something, can anyone help?

1
  • The JavaScript code is legal TypeScript code. What's the problem? Commented Jan 26, 2016 at 3:22

1 Answer 1

1

If you want to use a class, then make the property static so that it can be shared across all instances of the class and don't set it back to {} each time a new instance is created:

class MyService {
    static persistentData: any = {};

    saveData = (data: any) => {
        MyService.persistentData = data;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.