如何在连接器中访问不同的模型?

我离成功很近了,但就是卡住了。我已经在 connectors/revision-user-details-after 创建了一个连接器:

在我的连接器类中,我可以通过 shouldRender 方法访问 argscomponent,从而获取当前用户名和帖子 ID:

export default {
  shouldRender(args, component) {
    console.log('postAuthor', args.model.username)
    console.log('postId', args.model.id)
  }
};

我还想获取编辑该帖子的用户(在此例中为 “nachocab”)的用户名,但 args.modelPost 对象,而不是 PostRevision 对象。

历史记录弹窗的界面如下:

https://github.com/discourse/discourse/blob/main/app/assets/javascripts/discourse/app/templates/modal/history.hbs#L5

历史记录控制器如下:

https://github.com/discourse/discourse/blob/main/app/assets/javascripts/discourse/app/controllers/history.js#L74

我该如何在连接器中访问修订版本(revision)?

1 个赞

啊,我刚刚意识到我可以这样做!

import Post from "discourse/models/post";

Post.loadRevision(args.model.id, args.model.version).then((result) => {
  const editorUsername = result.username;
  doSomethingElse();
});

更新
@eviltrout 我原以为已经解决了这个问题,但刚刚意识到,由于 Post.loadRevision 返回的是一个 Promise,我无法将其放在 shouldRender() 中:

import Post from 'discourse/models/post';

export default {
  shouldRender(args, component) {
    // 返回 Promise 不起作用
    return Post.loadRevision(args.model.id, args.model.version).then((revision) => {
      return args.model.username !== revision.username;
    });
  },
};

还有其他方式可以实现吗?

你可以将其从连接器中移出,放入一个新插入的组件中,并在 Promise 完成前显示“加载中…"状态;待 Promise 完成后,再使用 set 设置该值并展示出来。

1 个赞

谢谢,Robin。你的提示正是我需要的。:tada:

这确实能工作,但我想知道是否真的需要直接的 ajax 调用(当我走连接器路径时,我可以访问 Post 但无法访问 Revision;现在改走组件路径后,我可以访问 Revision,却失去了对 Post 的访问权限 :thinking:

{{! templates/connectors/revision-user-details-after/reply-to-editor.hbs }}
{{reply-to-editor
  postId=model.post_id
  postVersion=model.current_version
  revisionAuthor=model.username
}}
{{! templates/components/reply-to-editor.hbs }}
{{#if isVisible}}
  {{d-button
    action=(action 'replyToEditor')
    label='test'
  }}
{{/if}}
{{! javascripts/discourse/components/reply-to-editor.js.es6 }}
import { ajax } from 'discourse/lib/ajax';

export default Ember.Component.extend({
  isVisible: true,

  didRender() {
    if (!this.get('postId')) return;

    ajax(`/posts/${this.get('postId')}`).then((post) => {
      // 仅当修订作者不是帖子作者时才显示按钮
      this.set('isVisible', this.get('revisionAuthor') !== post.username);
    });
  }
});

我不确定为什么你在模板中无法访问与连接器相同的变量。它们应该完全一致!