Difference between var declaration


#1

Hi there,

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

@Injectable()
export class MyService { … }

@Injectable()

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,
Mirco


#2

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) {
(i.e)

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)


#3

Hi maxx0r,

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

this.platform.ready().then(() => {
          somefunction();
        });

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


#4

Use

this.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.


#5

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

@Component({
  selector: 'page',
  templateUrl: 'page.html'
})
export class SomePage {

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

  ngOnInit() {
    this.platform.ready().then(() => {
      this.myService.doSomething();
    });
  }

And the Service

let otherStr = "bla";

@Injectable()
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);
  }

}


#6

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


#7

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