我开始关注ngrxstore ,我看到了使用Angular 异步管道的便利性.同时,我不确定大规模使用Angular 异步管道是否是一个好 Select .

我举一个简单的例子.假设在同一个模板中,我需要显示从存储中检索到的对象(例如人)的不同属性.

一段模板代码可以是

<div>{{(person$ | async).name}}</div>
<div>{{(person$ | async).address}}</div>
<div>{{(person$ | async).age}}</div>

而组件类构造函数将具有

export class MyComponent {
  person$: Observable<Person>;

  constructor(
    private store: Store<ApplicationState>
  ) {
      this.person$ = this.store.select(stateToCurrentPersonSelector);
  }
.....
.....
}

据我所知,这段代码意味着对同一个可观察对象(person$)进行3次订阅(通过异步管道在模板中进行).

另一种方法是在MyComponent中定义1个属性(person),并且只有1个订阅(在构造函数中)填充该属性,例如

export class MyComponent {
  person: Person;

  constructor(
    private store: Store<ApplicationState>
  ) {
      this.store.select(stateToCurrentPersonSelector)
                .subscribe(person => this.person = person);
  }
.....
.....
}

而模板使用标准属性绑定(即不使用异步管道),例如

<div>{{person.name}}</div>
<div>{{person.address}}</div>
<div>{{person.age}}</div>

Now the question

这两种方法在性能上有什么不同吗?大量使用异步管道(即大量使用订阅)会影响代码的效率吗?

推荐答案

无论是哪一种,都不应该将应用程序作为智能组件和表示组件来编写.

Advantages:

  • 智能控制器上的所有繁忙逻辑.
  • 只有一个订阅者
  • 可重用性
  • 呈现控制器只有一个责任,只呈现数据,并且不知道数据从何而来.(松散耦合)

Answering the last question:

异步管道的大量使用将影响效率,因为它将订阅每个异步管道.如果调用http服务,您会注意到这一点,因为它会 for each 异步管道调用http请求.

Smart Component

@Component({
  selector: 'app-my',
  template: `
      <app-person [person]="person$ | async"></app-person>
`,
  styleUrls: ['./my.component.css']
})
export class MyComponent implements OnInit {

    person$: Observable<Person>;

    constructor(private store: Store<ApplicationState>) {}

    ngOnInit() {
        this.person$ = this.store.select(stateToCurrentPersonSelector);
    }

}

Presentation Component

@Component({
  selector: 'app-person',
  template: `
    <div>{{person.name}}</div>
    <div>{{person.address}}</div>
    <div>{{person.age}}</div>
`,
  styleUrls: ['./my.component.css']
})
export class PersonComponent implements OnInit {

    @Input() person: Person;

    constructor() {}

    ngOnInit() {
    }

}

有关更多信息,请查看:

Angular相关问答推荐

仅在从forkJoin获得数据后订阅主题

带有搜索功能的CDK-VIRTUAL-SCROLL-VIEPORT不显示该值

独立组件;依赖项注入

Angular 16:CSRF配置:我仍然可以使用HttpXsrfInterceptor和HttpXsrfCookieExtractor类吗?Inteli-J说他们不存在

为什么在回调完成之前,可观察对象会返回?

Angular 17多内容投影错误

ANGLE v16独立组件不能与拦截器一起工作?

当try 关闭浏览器选项卡时显示alert 时,我是否可以捕获用户是否取消警告

npm install命令在基本Angular 应用程序的天蓝色构建管道中失败

无法使用@ngrx/component-store 在其他组件中获取状态更改值

如何处理Angular 延迟订阅

我想将一个对象传递给一个子组件.我做了一切,但没有任何效果. (Angular )

如何以像素为单位将属性绑定到 style.width?

无法绑定到matMenuTriggerFor,因为它不是 button的已知属性

导航到同一条route路由不刷新组件?

Angular2 中的providers提供者是什么意思?

Angular将 Select 值转换为 int

Angular 2+ ngModule 中导入/导出的作用

Angular2延迟加载模块错误'找不到模块'

RxJS - 发生错误时观察到的不会完成