Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for Angular 2 in TypeScript

I'm trying to rewrite my app in Angular 2 typescript and would like to use best practices. I've found the following guide but it doesn't answer my very basic questions. Here is two questions:

  1. In Components, is it ok to declare a local variable inside a function or should I declare it as private, right above the constructor?
  2. How should I call variables inside nested functions? For example:

    replicator(){// return observable}
    myFunction(){// Nested function to be called}
    
    ngOnInit() {
        this.replicator().subscribe(function (data) {
            // Call function here
        }
    }
    

    Should I call my function by doing: let self = this before this.replicator() and then call self.myFunction()? Or is there a better way to do this?

PS If you have a good best practice guide, please post it as a comment!

like image 382
ncohen Avatar asked May 20 '26 21:05

ncohen


1 Answers

How should I call variables inside nested functions

Use an arrow function (more).

ngOnInit() {
    this.replicator().subscribe((data) => {
        // Call function here
        this.somefunction
    }
}

is it ok to declare a local variable inside a function or should I declare it as private, right above the constructor

Both are fine. Local if its only local to the function or private if other functions might need it 🌹

like image 86
basarat Avatar answered May 23 '26 14:05

basarat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!