我正在尝试让一个数组由我的服务器管理并共享给我的客户端。我认为Meteor.methods()将通过创建一个getter方法来实现。 虽然由于某种原因,它由服务器正确打印到控制台,但当我执行Meteor.call()时返回undefined到客户端
,无论if是true还是false,我都会得到未定义的返回值。{{ form.cost }}
Meteor.methods()中的另一种方法完美无缺,我似乎无法弄清楚为什么这个方法没有看到,因为它做得少得多。
///server
Meteor.methods({
createNewUser: this.createNewUser,
getRoles: this.getRoles
});
...
getRoles(id) {
console.log(roles);
if (Roles.userIsInRole(id, "admin")) {
return roles;
} else {
return 'blah';
}
}
///client
ngOnInit() {
MeteorObservable.autorun().subscribe(() => {
...
Meteor.call("getRoles", Meteor.userId(), (data) => {
console.log("data", data);
this.roles = data;
console.log("roles", this.roles);
});
console.log("user list", this.userList);
console.log("roles", this.roles);
....
});
感谢您的帮助。
答案 0 :(得分:1)
Meteor.call是异步的,因此您之后立即执行的日志记录会在返回数据之前执行。您已经设置了回调,您应该在那里查找返回的数据。
此外,一旦回调内部,请注意使用“this”。这可能不是你所期望的那样。
答案 1 :(得分:0)
原来我的问题出在Method.call()
中它返回错误和结果,而不是单个对象。
///client
Meteor.call("getRoles", Meteor.userId(), (error, data) => {
if (!error) {
console.log("data", data);
this.roles = data;
console.log("roles", this.roles);
} else {
console.log("error: ", error);
}
});
///output
demo.component.ts:57 user list []
demo.component.ts:58 roles []
demo.component.ts:57 user list [Object]
demo.component.ts:58 roles []
demo.component.ts:49 data ["admin","spectator","coach","player"]
demo.component.ts:51 roles ["admin","spectator","coach","player"]
demo.component.ts:49 data ["admin","spectator","coach","player"]
demo.component.ts:51 roles ["admin","spectator","coach","player"]
demo.component.ts:57 user list [Object, Object, Object, Object, Object, Object]
demo.component.ts:58 roles ["admin","spectator","coach","player"]
demo.component.ts:49 data ["admin","spectator","coach","player"]
demo.component.ts:51 roles ["admin","spectator","coach","player"]
这就是我所期待的。(虽然不确定MeteorObservable被多次触发的原因。)