流星铁路由器动态段不工作

meteor iron router dynamic segment not working

本文关键字:段不 工作 动态 路由器 流星      更新时间:2024-04-05

我一直在观察流星,它太棒了!我一直在寻找路由解决方案,我发现了"铁路由器",这很酷,我设法让get静态页面与模板一起工作,但当我转到/posts/123时,页面不会呈现。我一直在关注这个网站的视频

https://www.eventedmind.com/feed/q8QWX5e7PTu8BEReY

这是我的代码

blog.js编辑

Posts = new Meteor.Collection('posts');
Router.configure({
  layout: 'layout',
  loadingTemplate: 'loading',
  notFoundtemplate: 'notFound'
});
Router.map( function (){
  this.route('posts', {
    path: '/',
    waitOn: function () {
      return App.subs.posts;
    },
    data: {
      posts: function () {
        return Posts.find({}, {sort: {order: 1}});
      }
    }
  });
  this.route('postShow', {
    path: '/posts/:_id'
  });
});
if (Meteor.isServer) {
  Meteor.publish('posts', function () {
    return Posts.find({}, {sort: {order: 1}});
  });
  Meteor.publish('post', function (id) {
    return Posts.find({_id: id});
  });
}
if (Meteor.isClient) {
  App = {
    subs: {
      posts: Meteor.subscribe('posts')
    }
  };
  PostShowController = RouteController.extend({
    template: 'postShow',
    before: function () {
      var _id = this.params._id;
      if(App.subs.post)
        App.subs.post.stop();
      App.subs.post = Meteor.subscribe('post', _id);
    },
    data: {
      body: function () {
        return Posts.findOne({_id: this.params._id});
      }
    },
    run: function () {
      this.render('postShow');
    }
  });
}

blog.html

<head>
    <title>IronRouter</title>
</head>
<body>
</body>
<template name="layout">
    <div class="container">
        <aside class="sidebar">
            <div class="sidebar-inner">
                {{yield 'sidebar'}}
            </div>
        </aside>
        <section class="content">
            <div class="content-inner">
                {{yield}}
            </div>
        </section>
    </div>
</template>
<template name="notFound">
  <h1>Not Found</h1>
</template>
<template name="loading">
  <h1>Loading...</h1>
</template>
<template name="posts">
  <h1>Posts</h1>
  <ul>
    {{#each posts}}
    <li>{{> postListItem}}</li>
    {{/each}}
  </ul>
</template>
<template name="postListItem">
    <a href="{{pathFor 'postShow'}}">
        {{title}}
    </a>
</template>
<template name="postShow">
  <p>
    {{body}}
  </p>
</template>
<template name="postShowSidebar">
  <h1>{{title}}</h1>
</template>

我是视频的作者,它可能有点过时了。我很抱歉。我会做以下事情:

  1. layout: 'layout'更改为layoutTemplate: 'layout'
  2. 从控制器中删除run方法。该方法实际上做了很多工作,因此如果要覆盖渲染,可以使用action方法。但在你的情况下,你不需要做任何事情,因为它会自动发生
  3. 这有点不相关,但你不需要自己停止订阅。事实证明,Meteor和iron路由器将在计算停止时(即,当您导航到新路线时)自动执行此操作

我希望这能有所帮助!

尝试将PostShowController添加到相应的路由:

this.route('postShow', {
  path: '/posts/:_id',
  controller: 'PostShowController'
});

也许我遗漏了什么,但在你的控制器中你说

data: function () {
  return Posts.findOne({_id: this.params._id});
},

但在您的模板中,您使用的是{{body}},我看它在任何地方都没有分配任何内容。不需要这样吗:

data: {
  body: function () {
    return Posts.findOne({_id: this.params._id});
  }
}