2016-04-15 111 views
5

我有一个简单的Meteor订阅,并且在加载数据时显示一条加载消息。但是,如果订阅失败,我不知道如何显示错误消息。Meteor 1.3 + React:检测订阅失败?

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); 

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

我知道Meteor.subscribe方法有一个onStop回调这种情况下,但我不知道如何粘贴它来传递一个属性。

+0

订阅没有失败的状态,他们只是提供一个数据集用于客户端数据库复制。我想你只想提供数据,如果一定条件得到满足。如果是这种情况,请独立检查条件,例如通过创建方法。 –

+0

他们必须有失败的状态。如果我错误输入了出版物名称,并且没有这种出版物,该怎么办? – aedm

+0

然后''onStop'回调被一个错误对象调用。 –

回答

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

在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); 

从这里所有你需要做的就是错误的道具,并根据需要呈现组件。

这是error支柱的结构(从subscribe接收到关于onStop回调):

{ 
    error: String, 
    reason: String, 
    details: String 
} 

[编辑]

的原因有一个条件周围Meteor.subscribe()是避免一个烦人的无限循环,你会从自然的withTracker()更新中获得,这会导致发布中的新订阅/新错误等。