错误:
错误:模板解析错误:解析器错误:绑定不能包含 作业在...。
行:
<div>Closed: {{blah}}.find()
...
HTML:
<div fxLayout="row" fxLayoutAlign="start center" fxLayoutGap="4px">
<div>Total: {{(issuesData$ | async)?.length}}</div>
<div>Closed: {{(issuesData$ | async)?.filter(data => {data.closedOn}).length}}</div>
</div>
我很好奇,如果在插值语句的集合上调用find / filter时是否可以使用find / filter而不遇到模板解析错误。
编辑: Angular 2 - Bindings cannot contain assignments-这对我不起作用,因为我将Observable传递给了组件。 OnInit我将@Input数据变量分配给可观察到的issueData $。在插值中使用类似{{getCount()}}之类的结果将没有数据。我尝试过这样实现:
英语:
@Input()
data;
ngOnInit() {
this.issuesData$ = this.data;
}
getCount(){
this.issuesData$.subscribe(data => {
return data.length;
})
}
HTML:
<div>Total: {{getCount()}}</div>
但是在插值中调用getCount()
时没有要订阅的内容,{{(getCount() | async}}
也不起作用
答案 0 :(得分:1)
您应该订阅Observable,然后在其中手动分配所需的变量,这纯粹是为了减少模板代码的复杂性。
@Input()
data;
total: number;
closed: number;
ngOnInit() {
this.issuesData$ = this.data;
this.issuesData$.subscribe(next => {
this.total = next.length;
this.closed = next.filter(x => x.closedOn).length;
}
}
然后只需在模板中使用total
和closed
变量即可。
答案 1 :(得分:1)
要从模板的异步数组中调用find
或filter
,请在组件类中定义回调。例如,您可以将方法isClosedOn
设置为filter
回调:
<div>Closed: {{ (issuesData$ | async)?.filter(isClosedOn).length }}</div>
并在组件类中对其进行如下定义:
public isClosedOn = data => data.closedOn;
有关演示,请参见this stackblitz。
答案 2 :(得分:1)
map
并以使组件/模板容易使用数据的方式格式化响应。subscribe
返回值,但是可以分配一个值。find
返回一个匹配项,filter
返回一个数组。如果您想使用filter
length
shareReplay
,则可观察对象将被解析一次,因此如果使用诸如外部资源之类的方法,则可以使用async
管道或subscribe
多次调用它,而不会产生额外的费用发出http请求。Template.html
<div>Total: {{(issuesData$ | async)?.length}}</div>
<div>Closed: {{(issuesData$ | async)?.closedOnLength}}</div>
YourComponent.ts
import { Observable } from 'rxjs';
import { map, shareReplay } from 'rxjs/operators';
@Input()
data: Observable<{closedOn:any}[]>;
issuesData$: Observable<{length: number, closedOnLength: number}>;
ngOnInit() {
this.issuesData$ = this.data.pipe(map((_) => {
return {
length: _.length,
closedOnLength: _.filter(d => d.closedOn).length
};
}), shareReplay());
}
count: number;
readCount() {
// you can't return data in a subscribe callback, it is asynchronous
// you can assign a value though
this.issuesData$.subscribe(_ => this.count = _.length);
}