Ionic 2 in ES6 - class level variable declaration


#1

Hi - dumb question this one.

I’m writing a quick Ionic 2 app for demo purposes and using ES6 because I don’t have time to familiarise myself with Typescript.

In this block of code,

`@Injectable()
export class TaskService {
static get parameters(){
return [[Http], [CurrentUserData], [LocalStorage]];
}

constructor(_http, _currentUserData, _localStorage) {
this._http = _http;
this._currentUserData = _currentUserData;
this._localStorage = _localStorage;`

which is obviously just a partial, where and how do I declare variables that I can access in any of my class functions. I tried putting them in the constructor but those get cleaned each time the service is called.

Any help would be greatly appreciated.

Tom


#2

Getting familiar with Typescript is easy as read a couple of articles of differences or features, and get some practice. I’m super happy now using it, and ionic CLI makes it all easy anyways. BTW, JS is not supported anymore from Ionic 2 beta9 onwards.

Basic service setup is:

@Injectable
export class MyService {
  varName: varType = initValue;

  constructor(
    private http: Http,
    private user: CurrentUserData,
    private storage: LocalStorage,
    params: NavParams
  ) {
    this.varName: params.get('paramName');
  }

  textMethod() {
    console.log(this.varName);
  }

Have fun! https://www.typescriptlang.org/docs/tutorial.html


#3

Hi Matheo

Totally agree with what you’re saying and I realise I need to do this.

However, is there any chance you could answer the question? I need to get this done and converting all the JS code I’ve already done to produce a working demo is not efficient at this point in time.

Tom


#4

Indeed, port a ton of code it’s not an easy job :worried:

What have you tried? this is supposed to work:

class MyClass {
  constructor(...) {
    ...
    this.myVariable = 'initial value';
  }

  yourMethod() {
    console.log(this.myVariable); // initial value
  }
}

#5

Yes I’ve tried that. The problem is that I’m using a service to maintain some global states and doing it this way resets the variable to the initial value each time the service is called. I need to set a class level variable outside the constructor.


#6

It sound to me like you’re not using a single instance of the Service for your app.

Angular 2 providers work as a singleton if you declare them once, but if you require them in multiple pages, each page will have a different instance. In your App providers, require your TaskService, then you can use Dependency Injection in any of your pages, and will be a single one for your app :wink:


#7

Yes, I’d done that with one service and forgotten with the other one.

Matheo, you are a star, thanks for your help.


#8

No problem Thomas! :slight_smile: