Difference between var declaration


Hi there,

I have a question about the difference of declaring a variable:
var authStr = “”;

export class MyService { … }


export class MyService {

authStr : string = “”;


Using nr. 2 leads sometime to this error (used in a function): Cannot set property ‘authStr’ of undefined. Using nr. 1 not.
What is the difference between this two possibilities?

Thanks in advance,


It’s all about scope. I think you get the error on the second one with callbacks (ie in promises) when using
.then(function(res) {

read up on scopes, your live will be easier. And you should never use var anymore. Use let. And don’t define variables outside classes in which you use them. Globals are bad.

(might sound offensive, but trust me, scoping wrong is something that might screw up your application in a very bad way)


Hi maxx0r,

thanks for your fast answer. I want to do something automatically on App start. So I used

this.platform.ready().then(() => {

And this seems to bring me out of scope. I’m not able to use the second possibillity of variable declaration in my somefunction().




You are trying to access a property of the class, you should use this. then ( :wink: ). When you are in the function scope, you can leave it out.


Yes, I’m using this. But here the details:

  selector: 'page',
  templateUrl: 'page.html'
export class SomePage {

  constructor(public navCtrl: NavController, private myService: MyService) {

  ngOnInit() {
    this.platform.ready().then(() => {

And the Service

let otherStr = "bla";

export class MyService {

  authStr: string = "bla";
  logonView: any;
  constructor(public http: Http) {}

  doSomething() {
    this.logonView = sap.logon.IabUi; // Usage of the external lib is the reason for this.platform.ready()
    console.log("Here is the problem " + this.authStr);
    console.log("This works " + otherStr);



Did you import the service in your app module and added a reference in you page??


yes, in app.modules.ts under providers and as a “normal” import statement in the page.