我在网上遇到的所有样本都是SPA,我想知道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 }
])
和post post就像这样
@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 },
])
答案 0 :(得分:1)
我想我理解你的问题。您需要以某种方式配置Web服务器软件(例如,Apache),这不是Angular2配置问题。您需要配置您的Web服务器,以便每当它收到像/或/ posts或/ posts / 123这样的url请求时,它就会为您的主index.html文件提供服务。然后Angular会在启动时自动显示正确的内容。
答案 1 :(得分:0)
好像你正在寻找路由器。看看文档: Off. Guide和Router Tutorial。它的使用方式如下:
@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 { }
答案 2 :(得分:0)
当你要求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
所需的资源所以简而言之,如果需要/询问路径退出,那么用户将走上这条道路。
答案 3 :(得分:0)
我知道我迟到了一年,但问题在于,您使用的网络服务器需要将网址重写为网络应用的index.html。如果它这样做,那么当你去server / hero / 123时,web服务器会将它引导到你的web-app的index.html,你的web-app将使用路由器转到HeroDetail组件,没有显示默认的主组件。由于您没有重写,因此网络服务器甚至没有启动角度应用,而是尝试提供 文件 服务器/ hero / 123,它不存在,因此它给你一个404.
仅供参考,这仍然是SPA(单页申请)。