Nav*_*med 5 observable angular2-template angular2-services ngrx angular
我使用 observable 将列表从服务返回到我的组件,在我的组件中我使用 ChangeDetectionStrategy.OnPush 并且在模板中我使用异步管道,希望这会带来一些性能优势,因为更改检测不是一直执行但仅当有新内容可用时。
以下是我的服务:
import { Injectable, Inject, EventEmitter } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class ListService {
public _list$: Subject<any[]>;
private list: any[] = [];
constructor() {
this._list$ = <Subject<any>>new Subject();
}
get list$() {
return this._list$.asObservable();
}
loadList() {
//if this.list is populated through an http call the view is updated,
//if its a static list like below, it doesn't trigger view update.
//this.list = ['Red', 'Green', 'Yellow', 'Blue'];
this._list$.next(this.list);
}
}
Run Code Online (Sandbox Code Playgroud)
在我的组件中,我有:
import { Component, ChangeDetectionStrategy } from '@angular/core';
import { Observable } from 'rxjs/Observable';
@Component({
templateUrl: `
<ul>
<li *ngFor="let item of (list$ | async);">
{{item}}
</li>
</ul>
`,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ListComponent {
public list$: Observable<any[]>;
constructor(
private _ls: ListService
) {}
ngOnInit() {
this.list$ = this._ls.list$;
this._ls.loadList();
}
}
Run Code Online (Sandbox Code Playgroud)
如果 loadList 内容通过 http 调用获取列表内容,则该问题会更新视图,如果列表内容是静态的,则不会更新视图。
如果我在 setTimeout 内包装列表更新,它会触发视图更新
setTimeout(() => {
this._list$.next(this.list);
}, 1);
Run Code Online (Sandbox Code Playgroud)
我刚开始探索 Observables,有人能指导一下上面的代码有什么问题吗?
只需将代码ngOnInit()从构造函数移至即可。Angular 尝试在调用之前解析绑定(订阅可观察的)ngOnInit()并失败,因为thod._list$它null无法识别更改,并且稍后不会尝试。