Search code examples
angulartypescriptrxjsimmutabilityobject-oriented-analysis

Assign value of a subscription to the property of a class without mutation


Up until now I have been doing the following to assign the value of a subscription to a property on my classes:

export class ExampleComponent implements OnInit {
  exampleId: string;

  constructor(public route: ActivatedRoute) {
    this.route.params.subscribe((params: Params) => this.exampleId = params.id);
  }

  ngOnInit() {
    // Do something with exampleId here...
  }
}

In an effort to move away from mutation and more towards immutability; I hope to assign the value that is returned from that subscription to the exampleId property without needing to do so in the constructor.

What is the best way to go about this?


Solution

  • Any asynchronous request you make from the constructor means your Component won't be immutable: it necessarily has two states; before and after the data has resolved.

    Therefore if you want an immutable component you have to move the asynchronous part out of the Component and fetch the data before it is constructed. For the example you gave this can be done using a routing Resolve service and a resolve object in the routing configuration. Then the router will resolve the data before the component is instantiated and it can be accessed through ActivatedRouteSnapshot.data.

    For a more general case to make any class immutable when that class depends on asynchronous data, you need some kind of factory that will resolve the data and make it available to the class on construction (here the router is that factory).