Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript make variable act as pointer to another variable

Lets say I have some component:

@Component({
    selector: 'my-view',
    templateUrl: './view.component.html',
    styleUrls: ['./view.component.scss']
})

export class ViewComponent implements OnInit {
    // used to alias the actual user data, set with OnInit
    private plan: string;
    private status: string;
    private started: string;
    private cycle: string;

    constructor (private auth: Auth, private modal: Modal, private router: Router) {}

    ngOnInit(): void {
        // without these shorthand names the components code would be messy and unreadable
        this.plan = this.auth.userProfile.user_metadata.plan;
        this.status = this.auth.userProfile.user_metadata.token.status;
        this.started = this.auth.userProfile.user_metadata.token.epoch;
        this.cycle = this.auth.userProfile.user_metadata.cycle;

        // do stuff using alias variables so I don't have to use extremely long names
        if(this.plan === .... && this.cycle === ...) {

        }
    }
}

This scenario allows me to use much shorter and simpler variable names instead of the long names I would normally use to access user data, But this breaks when the user data is updated while on this page.

Since the alias variables are only set during onInit, when a change to the user data occurs these variables don't reflect that change and the user would need to refresh the whole page to see the change.

Is there any way to easily do something like this, but have the variables like plan, status, started, cycle observe the original value and update accordingly? Otherwise I'd need to use the long names and sacrifice the readability of my code.

like image 548
Syntactic Fructose Avatar asked Feb 05 '17 17:02

Syntactic Fructose


1 Answers

Primitive values like string, number, boolean are always passed by value. Objects are passed by reference. It seems what you want is "pass by reference" for primitive type.

What you can do is to wrap the values with an object and pass that object instead.

It's usually a better way to use observables to notify interested other class instances about value changes.

For examples see https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

like image 103
Günter Zöchbauer Avatar answered Sep 25 '22 23:09

Günter Zöchbauer