我试图从一个observable初始化一个数组。但是我收到编译错误说:
组件:
export class LeaderBoardComponent implements OnInit {
leaderBoardTableData: Array<LeaderBoardModel>;
constructor(private appStore: Store<AppStore>,
private leaderBoardService: LeaderBoardService) {
this.leaderBoardService.getLeaderBoard()
.skipWhile((data) => { return _.isEmpty(data) })
.subscribe((data) => {
if (!_.isEmpty(data)) {
this.leaderBoardTableData = this.leaderBoardService.getLeaderBoard();
}
});
}
服务:
getLeaderBoard(): Observable<LeaderBoardModel> {
return this.httpUtil.get(this.appConstants.END_POINT_LEADERBOARD)
.map(response => <LeaderBoardModel>response.json());
}
答案 0 :(得分:3)
getLeaderBoard()
方法返回单个LeaderBoardModel
元素的可观察对象。因此,在订阅时,您必须将订阅的值(data
)推送到组件中的leaderBoardTableData
。
我认为应该是:
.subscribe((data) => {
if (!_.isEmpty(data)) {
this.leaderBoardTableData = [data];
// or `this.leaderBoardTableData.push(data);` , you have to make sure that `leaderBoardTableData` is already instantiated though
}
});
答案 1 :(得分:0)
您必须订阅this.leaderBoardService.getLeaderBoard()
,因为您无法将Observable分配给数组。
在代码中这样做:
this.leaderBoardService.getLeaderBoard().subscribe(data => {
this.leaderBoardTableData = data;
});
如果您希望leaderBoardTableData
等于一个observable,以便您的代码不必更改,您只需更改类型定义:
leaderBoardTableData: Array<LeaderBoardModel>;
要:
leaderBoardTableData: Observable<LeaderBoardModel>;
还要认识到你有一个通用的Array
类型,这意味着你的observable的返回值也必须是通用的Array
类型,否则你将得到一个类似的类型检查错误编译器。