Meteor 1.3 + React:检测订阅失败?

aed*_*edm 5 meteor meteor-publications meteor-react

我有一个简单的Meteor订阅,我在加载数据时显示加载消息.但是,如果订阅失败,我不知道如何显示错误消息.

export const MyAwesomeComponent = createContainer(() => {
  let sub = Meteor.subscribe('some-data');
  if (!sub.ready()) return { message: 'Loading...'};
  if (sub.failed()) return { message: 'Failed.' }; // How to do this?
  return {
    data: Data.find().fetch()
  }
}, MyInternalRenderComponent);
Run Code Online (Sandbox Code Playgroud)

问题是,订阅对象没有failed()方法,只有ready()查询.如何将订阅失败作为createContainer()方法中的道具传递?

我知道这个Meteor.subscribe方法有一个onStop回调用于这种情况,但我不知道如何粘合它以传递属性.

Raf*_*ite 0

经过大量研究后,我设法使其正常工作,我认为它回答了您的问题。

请记住,我使用的是 Meteor 1.6,但它应该为您提供信息以使其在您这边工作。

关于出版/出版:

  try {
    // get the data and add it to the publication
    ...
    self.ready();
  } catch (exception) {
    logger.error(exception);
    // send the exception to the client through the publication
    this.error(new Meteor.Error('500', 'Error getting data from API', exception));
  }
Run Code Online (Sandbox Code Playgroud)

在 UI 组件上:

const errorFromApi = new ReactiveVar();

export default withTracker(({ match }) => {
  const companyId = match.params._id;
  let subscription;

  if (!errorFromApi.get()) {
    subscription = Meteor.subscribe('company.view', companyId, {
      onStop: function (e) {
        errorFromApi.set(e);
      }
    });
  } else {
    subscription = {
      ready: () => {
        return false;
      }
    };
  }

  return {
    loading: !subscription.ready(),
    company: Companies.findOne(companyId),
    error: errorFromApi.get()
  };
})(CompanyView);
Run Code Online (Sandbox Code Playgroud)

从这里您需要做的就是获取 error 属性并根据需要渲染组件。

这是 prop 的结构(在回调error中收到):onStopsubscribe

{
  error: String,
  reason: String,
  details: String
}
Run Code Online (Sandbox Code Playgroud)

[编辑]

存在条件的原因Meteor.subscribe()是为了避免自然更新带来的恼人的无限循环withTracker(),这会导致新的订阅/发布的新错误等等。