学习Angular2所以请不要吝啬
因此,假设我的UserComponent
正在导出类型为User
的用户。它来自UserService
ngOnInit
。它有2个名为height
和weight
的属性。
在我的模板中,我想显示{{ user.score }}
,其中score
来自height
和weight
。我正在使用一个以height
和weight
为参数并返回分数的函数。
我的问题是,我在哪里声明score
?如果我在ngOnInit
循环中执行此操作则无效。
感谢您帮助初学者
export class UserComponent implements OnInit {
user = new User;
charId: number;
private sub: any;
constructor(private route: ActivatedRoute, private userService: UserService) {}
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
this.userId = params['id'];
this.userService.getUser(this.charId)
.subscribe(
(user: User) => {
this.user = user
});
});
}
}
// and the service
getUser(userId) {
return this.http.get('http://localhost:3000/user' + userId)
.map((response: Response) => {
const user = response.json().obj;
return user;
})
.catch((error: Response) => Observable.throw(error.json()));
}
答案 0 :(得分:1)
如果您拥有所需的数据(即订阅返回后
),您应该计算得分{{1}}
答案 1 :(得分:0)
根据您的评论,请尝试以下方式:
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
this.userId = params['id'];
this.userService.getUser(this.charId)
.subscribe(
(user: User) => {
this.user = user;
this.calcScore(this.user.height, this.user.weight);
});
});
}
calcScore(height, weight) {
this.user.score = YOUR_CALC
}
希望这会有所帮助。
答案 2 :(得分:0)
http://api.jquery.com/jquery.ajax/
在模板中显示为:
export class UserComponent implements OnInit {
user = new User;
charId: number;
private sub: any;
constructor(private route: ActivatedRoute, private userService: UserService) {}
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
this.userId = params['id'];
this.userService.getUser(this.charId)
.subscribe(
(user: User) => {
this.user = user;
this.user.score=calcScore(this.user.height, this.user.weight);//do it here
});
});
}
}
// and the service
getUser(userId) {
return this.http.get('http://localhost:3000/user' + userId)
.map((response: Response) => {
const user = response.json().obj;
return user;
})
.catch((error: Response) => Observable.throw(error.json()));
}
由于用户将通过异步操作进行设置,因此将在生成视图后进行。 Angular将在检测到更改后设置它