无法使用 Iron Router 访问 Meteor 中的参数
Cannot access params in Meteor with Iron Router
我有 'articles' 的列表视图和详细视图。这些是路线
this.route("articles", {path: "/articles", controller: "ArticlesController"});
this.route("article", {path: "/articles/:_id", controller: "ArticleController"});
在 /articles 的模板中,我有一个 link 详细视图
<a href="{{pathFor 'article' id=this._id }}"><i class="portlet-icon portlet-icon-maximize"></i></a>
页面已正确呈现并嵌入了 id,例如:
<a href="/articles/gb6KgxbnfBeynz4rH">
<i class="portlet-icon portlet-icon-maximize"></i>
</a>
在我与路由关联的控制器中,我无法访问参数,它是空的。
this.ArticleController = RouteController.extend({
template: "Article",
onBeforeAction: function() {
this.next();
},
action: function(){
if (this.isReady()) {
this.render();
} else {
this.render("loading");
}
},
isReady: function() {
var ready = true;
var subs = [ Meteor.subscribe('singleArticle')];
_.each(subs, function(sub) {
if(!sub.ready())
ready = false;
});
return ready;
},
data: function() {
console.log(Iron.Location.get());
console.log("params: " + this.params);
return {
article: Articles.findOne({articleId:this.params._id}, {})
};
}
});
从 Javascript 控制台我可以看到 _id 是通过 url 传递的,但我无法访问 this.params
问题是您使用的是 console.log
:
console.log("params: " + this.params);
params对象实际上是一个长度为零的数组。您可以在这里阅读有关它的讨论:https://github.com/iron-meteor/iron-router/issues/1213
因此您可以对单个参数使用 console.log,它会起作用:
console.log("params._id: " + this.params._id);
或者您可以使用:
console.dir("params: " + this.params);
我有 'articles' 的列表视图和详细视图。这些是路线
this.route("articles", {path: "/articles", controller: "ArticlesController"});
this.route("article", {path: "/articles/:_id", controller: "ArticleController"});
在 /articles 的模板中,我有一个 link 详细视图
<a href="{{pathFor 'article' id=this._id }}"><i class="portlet-icon portlet-icon-maximize"></i></a>
页面已正确呈现并嵌入了 id,例如:
<a href="/articles/gb6KgxbnfBeynz4rH">
<i class="portlet-icon portlet-icon-maximize"></i>
</a>
在我与路由关联的控制器中,我无法访问参数,它是空的。
this.ArticleController = RouteController.extend({
template: "Article",
onBeforeAction: function() {
this.next();
},
action: function(){
if (this.isReady()) {
this.render();
} else {
this.render("loading");
}
},
isReady: function() {
var ready = true;
var subs = [ Meteor.subscribe('singleArticle')];
_.each(subs, function(sub) {
if(!sub.ready())
ready = false;
});
return ready;
},
data: function() {
console.log(Iron.Location.get());
console.log("params: " + this.params);
return {
article: Articles.findOne({articleId:this.params._id}, {})
};
}
});
从 Javascript 控制台我可以看到 _id 是通过 url 传递的,但我无法访问 this.params
问题是您使用的是 console.log
:
console.log("params: " + this.params);
params对象实际上是一个长度为零的数组。您可以在这里阅读有关它的讨论:https://github.com/iron-meteor/iron-router/issues/1213
因此您可以对单个参数使用 console.log,它会起作用:
console.log("params._id: " + this.params._id);
或者您可以使用:
console.dir("params: " + this.params);