了解路由器插座

时间:2017-10-05 08:06:22

标签: c# asp.net angularjs

我想将带有Razor页面的ASP.NET MVC 5应用程序迁移到带有ASP.NET Core的Angular应用程序。好吧,我是从头开始做的。

这是我第一次使用Angular,我使用 Visual Studio ASP.NET核心Web应用程序模板创建了一个新应用程序,选择 Angular 选项并使用C#,ASP.NET Core 2.0,Visual Studio Professional 15.3.5。

命令 ng --version 返回:

@angular/cli: 1.4.4
node: 6.11.3
os: win32 x64

我找到了关于该模板here的教程,但有一件事我不明白:

有一个名为home的选择器的主组件,但它不会在任何其他组件中使用,它仍然会被渲染。

app.component.html我发现了这个:

<div class='container-fluid'>
    <div class='row'>
        <div class='col-sm-3'>
            <nav-menu></nav-menu>
        </div>
        <div class='col-sm-9 body-content'>
            <router-outlet></router-outlet>
        </div>
    </div>
</div>

我认为<router-outlet></router-outlet>负责呈现app.component.html,但我不确定它是如何运作的。

它是渲染家庭组件,因为我在主页(/)?如果是这样,如果我不在主页,它是如何工作的?使用RouterModule文件中的app-module值?

1 个答案:

答案 0 :(得分:0)

查看你提到的教程

RouterModule.forRoot([
        { path: '', redirectTo: 'home', pathMatch: 'full' },
        { path: 'home', component: HomeComponent },
        { path: 'counter', component: CounterComponent },
        { path: 'fetch-data', component: FetchDataComponent },
        { path: '**', redirectTo: 'home' }
    ])

path: '**'是默认设置,redirectTo: 'home'

来自router docs

  

最后一条路线中的**路径是通配符。路由器将选择   如果请求的URL与路由的任何路径不匹配,则为此路由   在配置的早期定义。这对于显示a非常有用   “404 - Not Found”页面或重定向到另一条路线。

您正在查看的教程不是angularcli,如果您使用ng new选项运行--routing,它将包含路由位,请参阅stories routing

这将生成app-routing.module.ts没有路由,如果您导航到localhost:4200/test它将以localhost:4200结束,但您会在控制台中看到错误(因此,这是路由它就像未处理的异常处理一样工作)

error, could not find any routes. URL segment : 'test'

现在看来,我来自ASP.NET背景,我创建了一个项目,你链接到tutorial。它工作,然后我很头疼转向Angular 4.我现在做的是。

  1. 使用CLI在自己的文件夹中创建一个纯Angular应用程序
  2. 为我的API创建MVC应用
  3. 设置代理以将/ api路由到您的MVC应用程序(FOR DEV)
  4. 让生产工作(你可以稍后再做)

    1. 向MVC应用添加代码,将所有未找到的错误路由到index.html
    2. 使用ng --prod build进行构建时,请将文件输出到wwwroot以获取MVC应用。