你如何发布和订阅不是Mongo db的数据?

时间:2018-06-10 05:15:43

标签: reactjs meteor

使用Meteor.publish设置执行某些异步请求(例如API)然后返回要在React组件中显示的数据的过程是什么?发布如何工作以及客户端代码如何访问它?如果可能的话,我想用withTracker函数来做这件事。谢谢!

1 个答案:

答案 0 :(得分:1)

本指南应该有所帮助:Publications and Data Loading

基本上,您需要了解Meteor的low-level API如何工作,以便您知道如何将您想要的任何数据集发布到客户端Mongo集合中。此外,要从其他API端点发布数据,本指南的this part显示了一个非常明确的示例。

至于在客户端订阅这种定制的出版物,它就像你从典型的MongoDB类型出版物订阅一样简单。请注意,正如我上面提到的那样,差异在于您从Client-side collection发布/订阅。

下面是我自己写的一个简单例子。我真的不知道React,但客户端代码主要基于Meteor的教程:

/* client side */
import React, { Component } from 'react';
import { withTracker } from 'meteor/react-meteor-data';
import { Meteor } from 'meteor/meteor'; 
import { Mongo } from 'meteor/mongo';

const Foo = new Mongo.Collection('Foo');

class App extends Component {
  renderFoo() {
    return this.props.foos.map((foo) => (
      <Foo key={foo._id} foo={foo} />
    ));
  }
}

export default withTracker(() => {
  Meteor.subscribe('publishFromAnApi', ...args);
  return {
    foos: Foo.find().fetch(),
  };
})(App);


/* server side */
import { Meteor } from 'meteor/meteor';
import { HTTP } from 'meteor/http';

Meteor.publish('publishFromAnApi', function publishFromAnApi(...args) {  // must use a function instead of an arrow function here for the sake of `this`
  const publishedKey = {};
  const collectionName = 'Foo'; // same name of the client side collection mentioned in line 6

  const poll = () => {
    const { data } = HTTP.get('/some/api/route', { ...someArgsToRequest });
    for (let i = 0; i < data.responseFromAPI; i += 1) { // just a random example here, assuming responseFromAPI is an array
      const document = data.responseFromAPI[i];
      const id = <the id of the document; normally is in Mongo.ObjectID type>;

      // some logics might be going on...

      if (!publishedKey[id]) {
        this.added(collectionName, id, document);
        publishedKey[id] = true;
      } else {
        this.changed(collectionName, id, document);
      }
    }
  };

  poll();
  this.ready();

  const interval = Meteor.setInterval(poll, <poll interval>);

  this.onStop(() => {
    Meteor.clearInterval(interval);
  });
});