2016-04-15 110 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()更新中獲得,這會導致發佈中的新訂閱/新錯誤等。