简体   繁体   English

将订阅的值分配给没有突变的类的属性

[英]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.我希望将从该订阅返回的值分配给exampleId属性,而无需在构造函数中这样做。

What is the best way to go about this?解决这个问题的最佳方法是什么?

Any asynchronous request you make from the constructor means your Component won't be immutable: it necessarily has two states;您从构造函数发出的任何异步请求都意味着您的Component不会是一成不变的:它必须具有两种状态; 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.因此,如果您想要一个不可变的组件,您必须将异步部分移出Component并在构造之前获取数据。 For the example you gave this can be done using a routing Resolve service and a resolve object in the routing configuration.对于您给出的示例,可以使用路由配置中的路由解析服务和resolve对象来完成此操作。 Then the router will resolve the data before the component is instantiated and it can be accessed through ActivatedRouteSnapshot.data .然后路由器将在实例化组件之前解析数据,并且可以通过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).对于在类依赖于异步数据时使任何类不可变的更一般情况,您需要某种工厂来解析数据并使其可用于构造类(这里的路由器就是该工厂)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM