NgrxStore和Angular - 大量使用异步管道或在构造函数中只订阅一次

Pic*_*cci 45 ngrx angular

我开始关注ngrx Store,看到使用Angular异步管道的便利性.同时我不确定是否大量使用Angular异步管道是一个不错的选择.

我举一个简单的例子.让我们假设在同一模板中我需要显示从Store检索的对象(例如Person)的不同属性.

一段模板代码可以

<div>{{(person$ | async).name}}</div>
<div>{{(person$ | async).address}}</div>
<div>{{(person$ | async).age}}</div>
Run Code Online (Sandbox Code Playgroud)

而组件类构造函数将具有

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

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

据我所知,这段代码暗示了3个订阅(通过异步管道在模板中制作)到同一个Observable(person$).

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

export class MyComponent {
  person: Person;

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

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

<div>{{person.name}}</div>
<div>{{person.address}}</div>
<div>{{person.age}}</div>
Run Code Online (Sandbox Code Playgroud)

现在的问题

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

Vic*_*doy 37

也不应该将应用程序组成智能和演示组件.

好处:

  • 智能控制器上的所有buissness逻辑.
  • 只需一个订阅
  • 可重用性
  • 演示控制器只有一个责任,只是提供数据,不知道数据来自何处.(松散耦合)

回答最后一个问题:

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

智能组件

@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);
    }

}
Run Code Online (Sandbox Code Playgroud)

演示组件

@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() {
    }

}
Run Code Online (Sandbox Code Playgroud)

欲了解更多信息:


mar*_*xin 13

另一种可能性是使用这样的结构:

<div *ngIf="person$ | async as per">
    <div>{{ per.name }}</div>
    <div>{{ per.address }}</div>
    <div>{{ per.age }}</div>
<div>
Run Code Online (Sandbox Code Playgroud)

虽然对于可重用的代码位,但使用表示组件方法可能更好.

请注意这是有角度的5,不确定其他版本.


Joh*_*amm 11

您可以在任何可观察声明的末尾添加".share()".然后,observable上的所有异步管道将共享相同的订阅:

this.name$ = Observable.create(observer => {
  console.log("Subscriber!", observer);
  return observer.next("john")
}).delay(2000).share();

this.httpget$ = http.get("https://api.github.com/").share();
Run Code Online (Sandbox Code Playgroud)

Plunkr演示:https://embed.plnkr.co/HNuq1jUh3vyfR2IuIe4X/