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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With