我想知道在模板中使用服务方法是否是Angular6中的反模式:
根据实例
component.ts
constructor(public myService: MyService) {}
component.html
<div>{{myService.getItems() | async}}</div>
答案 0 :(得分:2)
是的。您应该将方法返回的observable分配给组件中的属性,然后在模板中使用它。
myObservable$;
constructor(private myService: MyService) {}
ngOnInit() {
this.myObservable$ = this.myService.getItems();
}
在您的模板中:
<div>{{myObservable$ | async}}</div>
这样做有几个原因。
答案 1 :(得分:2)
在大多数情况下,由于注释中已经提供了原因,例如,可能是一个坏主意。 link Sachila发表或在答案中提到了Siddharth。
尽管如此,即使在Tour of Heroes中,它们也确实可以直接访问服务,但是似乎只是在访问属性而不是方法,特别是访问执行昂贵操作的方法。