2015-02-10 28 views
1

我有鐵路由器做了一個簡單的項目/任務應用中的以下路線:鐵路路由器,如何重定向到新創建的項目?

Router.route('/tasks/:_id', { 
    name: 'tasks.project', 
    template: 'tasks', 
    waitOn: function(){ 
    //subscribing to all user's projects and tasks 
    return [Meteor.subscribe('userTasks'),Meteor.subscribe('userProjects')]; 
    }, 
    onAfterAction: function(){ 
    //Session var used to show only tasks assigned to the project _id 
    Session.set('currentProject', this.params._id); 
    } 
}); 

當用戶創建一個新的項目,我想他重定向到相應的頁面(/任務/ XXXXXXXXX)。 所以,我在服務器上創建的方法和客戶端上的模擬像這樣:

//Server 
Meteor.methods({ 
    createProject: function(){ 
    Projects.insert({/*some data*/}, function (error, result) { 
    }); 
    } 
}); 

//Client 
Meteor.methods({ 
    createProject: function(){ 
    Projects.insert({/*some data*/}, function (error, result) { 
     //Router.go does not work (jumps briefly to /tasks/xxxxxxxxx, and comes back) (I verifiedn result corresponds to the new project id) 
     Router.go('tasks.project', {_id: result}); 
    }); 
    } 
}); 

我調用此方法是這樣的:

​​

在客戶端插入的Router.go功能不起作用。 我發現使這項工作的唯一方法是使服務器端插入同步並將Router.go放在方法調用回調中。就像在這個新版本:

//Server 
Meteor.methods({ 
    createProject: function(){ 
    //now synchronous 
    var id = Projects.insert({/*some data*/}); 
    return id; 
    } 
}); 

//Client 
Meteor.methods({ 
    createProject: function(){ 
    Projects.insert({/*some data*/}, function (error, result) {   
    }); 
    } 
}); 
Template.tasks.events({ 
    'click .create-project': function(event, template){ 
    Meteor.call('createProject', function(error, result){ 
     Router.go('tasks.project', {_id: result}); 
    }); 
    } 
}); 

但這重定向受服務器延遲,這是我想避免的。考慮到新的項目文檔是立即在客戶端集合中創建的,這要歸功於仿真方法,Iron路由器不能在第一版本的代碼中重定向嗎?或者我錯過了什麼?

回答

2

我認爲你的問題來自爲假客戶日期生成的_id和由服務器定義的真實_id之間的差異。事實上,_id是使用Meteor.uuid函數生成的,每次調用它時都會生成一個隨機ID。

因此,當您收到服務器響應並同步數據庫時,生成的假項目不再存在,並且已被實際的新項目(已保存在服務器上)替換爲不同的_id。所以,當發生這種情況時,您的路線指向不存在的項目。

然後您應該接受一些等待時間給用戶,或者至少在獲得服務器響應時將用戶重定向到正確的URL。因此,該代碼將是:

//Server 
Meteor.methods({ 
    createProject: function(){ 
    return Projects.insert({/*some data*/}); 
    } 
}); 

//Client 
Meteor.methods({ 
    createProject: function(){ 
    Projects.insert({/*some data*/}, function (error, result) { 
     //Router.go does not work (jumps briefly to /tasks/xxxxxxxxx, and comes back) (I verifiedn result corresponds to the new project id) 
     Router.go('tasks.project', {_id: result}); 
    }); 
    } 
}); 

以及活動

Template.tasks.events({ 
    'click .create-project': function(event, template){ 
    Meteor.call('createProject', function(error, result){ 
     Router.go('tasks.project', {_id: result}); 
    }); 
    } 
}); 
+0

我還以爲:第一,這是原因,但在兩個插入的結果做的console.log()的時候(客戶端和服務器端)我得到完全相同的ID。當Router.go跳轉到/ tasks/xxxxxxxx並返回時,它實際上跳轉到不改變的正確ID。 – Guillaume 2015-02-11 09:57:18

相關問題