Angular 2用于非SPA(静态页面)



我在网上看到的所有样本都是SPAs,我想知道Angular 2是否有一种内置的方式来处理静态页面。具体来说,假设我使用Angular 2来构建一个博客网站,我希望用户可以直接转到某个特定的帖子,而无需经过默认的主页组件(顺便说一句,它加载了大量服务器端配置)。我的意思是,我如何让用户转到http://server/posts/:id而没有404显示或配置用于不可达的**页面。

只是需要一些方向,谢谢。

假设我的文件夹结构类似于

/posts
/shared
/users

我的主路由器是这样的

@RouteConfig([
    { path: './shared/...', name: 'Shared', component: SharedComponent },
    { path: './users/...', name: 'Users', component: UserComponent },
    { path: './posts/...', name: 'Posts', component: PostComponent }
])

后路由器就像这个

@RouteConfig([
    { path: '/', name: 'List', component: ListComponent, useAsDefault: true },
    { path: '/:id', name: 'Post', component: PostComponent },
    { path: '/:id/gallery', name: 'Gallery', component: GalleryComponent },
    { path: '/:id/comments', name: 'Comments', component: CommentListComponent },
])

我想我理解你的问题。您需要以某种方式配置web服务器软件(例如Apache),这不是Angular2配置问题。你需要配置你的网络服务器,这样每当它收到像/或/posts或/posts/123这样的url请求时,它就会为你的主index.html文件提供服务。然后Angular将在启动时自动显示正确的内容。

看起来你在寻找路由器。查看文档:Off.指南和路由器教程。它是这样使用的:

@Component({ ... })
@RouteConfig([
  {path:'/crisis-center', name: 'CrisisCenter', component: CrisisListComponent},
  {path:'/heroes',        name: 'Heroes',       component: HeroListComponent},
  {path:'/hero/:id',      name: 'HeroDetail',   component: HeroDetailComponent}
])
export class AppComponent { }

当你要求without going through the default home component时,很难说出完美的答案(我不知道你的意思是什么)。

AFAIK,在angular2中,您可以有一个组件,该组件可以定义/设置其他组件的路线,以及它们的相关视图。


比方说,在单个组件中定义路由后,

如果您使用HashLocationStrategy,如下图所示,

bootstrap(AppComponent, [provide(LocationStrategy,{useClass: HashLocationStrategy}]);

Angular2将能够为您提供所需的路由,因此您不需要为服务器配置一些额外的路由设置。然后,您将能够访问所需的资源http://server/#/posts/:id


如果您使用PathLocationStrategy,如下图所示,

bootstrap(AppComponent, [provide(APP_BASE_HREF).toValue(location.pathname)]);

对于这种配置,angular2将无法为您提供所需的路由,因此需要配置服务器端路由。然后,您将能够访问所需的资源http://server/posts/:id

因此,简而言之,如果需要/询问路径退出,它会将用户带到该路径。

我知道我迟到了一年,但你的问题是,无论你使用什么web服务器,都需要将URL重写到你的web应用程序的index.html。如果它这样做了,那么当你转到server/hero/123时,网络服务器会将其引导到你的网络应用程序的index.html,你的web应用程序会使用路由器转到HeroDetail组件,而不显示默认的主页组件。因为您没有重写,web服务器甚至没有启动angular应用程序,而是试图为不存在的server/hero/123文件提供服务,因此它给您一个404。

仅供参考,这仍然是一个SPA(单页应用程序)。

最新更新