首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何发布和订阅非Mongo db的数据?

如何发布和订阅非Mongo db的数据?
EN

Stack Overflow用户
提问于 2018-06-10 13:15:43
回答 1查看 174关注 0票数 2

让Meteor.publish安装程序执行一些异步请求(例如应用程序接口),然后返回您想要在React组件中显示的数据,这是一个什么样的过程?发布是如何工作的,客户端代码如何访问它?如果可能的话,我想用withTracker函数来做这件事。谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-10 23:38:59

这个指南应该会有所帮助:Publications and Data Loading

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

至于在客户端订阅这种自定义发布,就像订阅典型的MongoDB类型发布一样简单。请注意,正如我在上面提到的,不同之处在于,您是在向Client-side collection发布/从a订阅。

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

代码语言:javascript
复制
/* 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);
  });
});

meteor

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50780760

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档