使用 angular-meteor 通过 Meteor.methods 在服务器和客户端之间发送数组

Sending array between server and client via Meteor.methods using angular-meteor

我正在尝试让一个数组由我的服务器管理并共享给我的客户端。我认为 Meteor.methods() 将是通过创建 getter 方法来实现的方法。 尽管出于某种原因它可以通过服务器正确打印到控制台,但是当我执行 Meteor.call() 时 returns 未定义给客户端 无论 if 是真还是假,我都会得到未定义的 returns,它总是未定义的。

///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);
....
});

Meteor.methods() 中的另一种方法非常有效,我似乎无法弄清楚为什么这个方法没有看到,因为它做的少得多。

///output
demo.component.ts:53 user list []
demo.component.ts:54 roles []
demo.component.ts:53 user list [Object]
demo.component.ts:54 roles []
demo.component.ts:48 data undefined
demo.component.ts:50 roles undefined
demo.component.ts:48 data undefined
demo.component.ts:50 roles undefined
demo.component.ts:53 user list [Object, Object, Object, Object, Object, Object]
demo.component.ts:54 roles undefined
demo.component.ts:48 data undefined
demo.component.ts:50 roles undefined

感谢您的帮助。

Meteor.call 是异步的,因此您之后立即执行的日志记录会在返回数据之前执行。您已经设置了回调,您应该在那里寻找返回的数据。

此外,一旦进入回调,请小心使用 "this"。这可能不是您期望的那样。

原来我的问题出在 Method.call()

它 returns 一个错误和一个结果,而不是单个对象。

    ///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 被触发了这么多次。)