使用 Angular2 和 RxJs 突出显示所选项目

Highlight selected item with Angular2 and RxJs

我正在重写一个简单的 Angular2 视图组件以使用 Observables 和异步管道。它显示了一个结果列表,并且有一个应该突出显示的选定结果。

在我的组件具有以下属性之前:

results: Result[] = [];
selectedResult: Result = null;

视图中的循环看起来像这样:

<div *ngFor="let r of results" [class.active]="r === selectedResult" />

现在我有了以下带有可观察对象的视图组件:

@Component({
    moduleId: module.id,
    selector: 'results-view',
    templateUrl: 'results-view.component.html'
})
export class ResultsViewComponent implements OnInit {

    constructor(private resultService: ResultService,
        private route: ActivatedRoute) { }

    results: Observable<Result[]> = null;
    selectedResult: Observable<Result> = null;

    private selectRequests = new Subject<string>();

    ngOnInit(): void {
        let deviceId = this.route.snapshot.params['deviceId']

        this.results = this.resultService.getResults(deviceId);
        this.selectedResult = Observable.combineLatest(this.selectRequests.asObservable(), this.results, (sr, res) => {
            return res.filter(r => r.resultId == sr)[0];
        });      
    }

    selectResult(resultId: string): void {
        this.selectRequests.next(resultId);
    }
}

以及以下视图:

<table class="table table-hover">
    <thead>
        <tr>
            <th>Alert</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let r of (results | async)" [class.active]="r === selectedResult">
            <td>{{r.Name}}</td>
            <td>
                <a href="javascript:void(0)" (click)="selectResult(r.resultId)"><span class="glyphicon glyphicon-search" aria-hidden="true"></span></a>
            </td>
        </tr>
    </tbody>
</table>

这是行不通的。我还尝试了 angular 表达式

"r === (selectedResult | async)"

但它也不起作用。唯一发生的事情是 getResults 方法针对服务器执行了多次。

使用可观察对象进行选择处理的正确方法是什么?

现在是这样工作的:

在视图中,我不再比较对象引用,而是比较对象的 ID(字符串)。所以视图中的循环看起来像这样:

<tr *ngFor="let r of (results | async)" [class.active]="r?.resultId == (selectedResult | async)?.resultId">

这给我留下了一个问题,即为每一行创建一个新的订阅,这反过来导致 getResult() 返回服务器。

我的第一次尝试是像这样修改我的可观察对象:

this.results = this.resultService.getResults(deviceId).share();

有趣的是,这仍然给我留下了两次返回服务器的调用(为什么???)。但是这个似乎工作正常:

this.results = this.resultService.getResults(deviceId).publishLast().refCount();

此解决方案的灵感来自 this 博客 post。

对于相同的结果,您可以使用属性指令。这是 link 会对你有所帮助。 https://angular.io/docs/ts/latest/guide/attribute-directives.html#!#bindings

只捕获 OnClick 事件而不是 OnMouseEnter() 事件。