【发布时间】:2019-12-20 21:41:21
【问题描述】:
在组件的模板中使用服务变量(如下面的代码)是个好主意吗?
问题是,当我尝试像这样在组件本身中定义这个变量时:usersList = this.service.arr,然后在这样的模板中使用:ngFor = let item of usersList。
如果没有一些额外的步骤,它就无法工作 - 例如,使用 Subject 。
@Injectable()
export class SomeService {
arr: SomeObject[];
constructor(private http: HttpClient) { }
getUsers() {
this.http.get('someUrl')
.subscribe(
res => arr as SomeObject[])
};
}
@Component({
selector: 'app-smth',
templateUrl: template: `
<ul *ngFor = "let item of service.arr">
<li>Name: {{item.name}}</li>
</ul> `
})
export class CategoryComponent implements OnInit, OnChanges {
constructor(private service: SomeService) { }
【问题讨论】:
-
service.arr将 never 在您的示例中除了undefined之外的任何东西,您的订阅实际上并未分配给它。如果该值一开始不可用,则公开一个 observable。 -
o.因为这是我的错误。它应该是这样的: res => res = arr as SomeObject[]。它以正确的方式工作。
标签: angular typescript