单视图页面永久链接为空,带有铁路由器

Single view page permalink empty with Iron Router

本文关键字:路由器 链接 视图 单视图      更新时间:2023-09-26

我在Iron-Router中设置了两条路由:"主页"(所有帖子的分页列表)和"doc"(详细信息视图)。主页加载正常,但只有在以前查看过主页的情况下才能加载详细信息视图。否则,它将呈现为空 - 并且不能用作永久链接。

这将始终加载:http://localhost:3000/

仅当之前查看过"主页"时,才会加载:http://localhost:3000/doc/tZFawq8cgf43hZBaJ

路线:

Router.map(function() {
    this.route('home', {
        path: '/'
    });
    this.route('doc', {
        path: '/doc/:_id',
        data: function() {
            return MyPix.findOne({_id: this.params._id});
        }
    });
});

文档模板:

<template name="doc">
    <h1>{{this.name}}</h1>
    <img src="{{ this.url store='OriginalRetinaPix' }}" width="{{ this.metadata.width }}" height="{{ this.metadata.height }}" />
</template>

发布/订阅:

Meteor.publish('MyPix', function(cursor) {
    Counts.publish(this, 'numberOfPosts', MyPix.find(), { noReady: true });
    return MyPix.find({}, {sort: {uploadedAt: -1}, limit: 4, skip: cursor});
});
if(Meteor.isClient) {
    Session.setDefault('docCursor', 0);
    console.log('docCursor: ' + Session.get('docCursor'));
    Meteor.autorun(function(){
        Meteor.subscribe('MyPix', Session.get('docCursor'));
    })
}

顺便说一句:GitHub上的项目

在您的"doc"路由上,您应该使用waitOn以便在页面加载时准备好数据。在Router.configure中添加加载模板

我建议升级到新的 iron:router 路由声明,并添加meteorhacks:subs-manager以更好地缓存订阅。

这是一个应该适用于您的案例的示例

var subs = new SubsManager();
Router.route('/doc/:_id', {
  name: 'doc',
  template: 'doc',
  waitOn: function() {
    return subs.subscribe('aPix', this.params._id);
  },
  data: function() {
    return {
      apix: MyPix.findOne({
        _id: this.params._id
      })
    };
  }
});

并在服务器端创建一个publications.js

Meteor.publish('aPix', function(id) {
  check(id, String);
  return MyPix.find(id);
});

使用这个。

Router.map(function() {
    this.route('home', {
        path: '/'
    });
    this.route('doc', {
        path: '/doc/:_id',
        waitOn: function(){ 
             return Meteor.subscribe('MyPix');
        },
        data: function() {
            return MyPix.findOne({_id: this.params._id});
        }
    });
});

此外,您的订阅应如下所示。

Meteor.publish('MyPix', function(cursor) {
    //Counts.publish(this, 'numberOfPosts', MyPix.find(), { noReady: true });
    return MyPix.find({});
});

还要添加,meteor add sacha:spin,因为当您有很多人时,订阅会有一些延迟。

将此添加到每个路由。

loadingTemplate: "loading"
<template name="loading">
    {{> spinner}}
</template>
Router.onBeforeAction("loading");

以防万一您在'home'上显示 100+ 张图片并且有人进入并且连接速度慢,他会认为页面加载是空的,或者其他什么。

您只订阅所有文档的子集。如果直接转到 /doc/tZFawq8cgf43hZBaJ ,具有 ID tZFawq8cgf43hZBaJ的文档可能不是您在客户端上收到的文档子集的一部分。

注意:如果此答案正确,您应该能够直接转到主页上首先显示的文档的/doc/<id>(在第一页上,当会话变量docCursor0时)。