我开始关注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)
现在的问题
这两种方法在性能方面有什么不同吗?是否大量使用异步管道(即大量使用订阅)会影响代码的效率?
在以下代码中:
RxJS.Observable.of(1,2).first().subscribe((x) => console.log(x););
Run Code Online (Sandbox Code Playgroud)
是否需要退订给特定的运营商first()?
我想问一下我的订阅方法。我想从 firebase 中获取我的对象(员工)并对我的对象进行大量操作,例如平均工资、平均缺勤天数……在我看来,这看起来太可怕了。我的服务无效:
getEmployees(): Observable<Employee[]> {
return this.db.list<Employee>(this.Api_url).snapshotChanges()
.pipe(map(response => response.map(car => this.assignKey(car))));
}
Run Code Online (Sandbox Code Playgroud)
还有我的 ngOnInit:
ngOnInit() {
this.subscribtion = this.mainservice.getEmployees().subscribe((emps)=> {
this.employees = emps;
this.workersdatas = [];
this.educationdatas = [];
this.checkavaragesalaries(emps);
this.countMonthAbsences(emps, 1);
this.countMonthSalaries(emps, 1);
this.departments.forEach((one)=> {
const dep = emps.filter(on => on.department.includes(one) && this.FilterEmployees(on)).length;
this.workersdatas.push({name: one, value: dep});
});
this.educations.forEach((one)=> {
const edu = emps.filter(on => on.education.includes(one)).length;
this.educationdatas.push({name: one, value: edu});
});
const mynumb =this.educationdatas.map(on => on.value);
this.mosteducation = this.educationdatas.filter(one => one.value === Math.max(...mynumb))[0].name;
}); }
Run Code Online (Sandbox Code Playgroud)
我应该在 ngOnDestroy …