angular 8:为什么组件没有加载?

angular 8 : Why the component is not loading?

所以我用 angular-cli 创建了一个应用程序。我在 src 目录中有以下结构。

. ├── app │   ├── app-routing.module.ts │   ├── app.component.css │   ├── app.component.html │   ├── app.component.spec.ts │   ├── app.component.ts │   ├── app.module.ts │   └── notifications │   ├── notifications.component.css │   ├── notifications.component.html │   ├── notifications.component.spec.ts │   └── notifications.component.ts ├── assets ├── environments │   ├── environment.prod.ts │   └── environment.ts ├── favicon.ico ├── index.html ├── main.ts ├── polyfills.ts ├── protocol.js ├── styles.css └── test.ts

路线有以下。

RouterModule.forRoot([
        { path: '', component: AppComponent },
        { path: 'notifications', component: NotificationsComponent}
    ])

AppComponent 有 Html 登录页面。
提交表单后,我使用 [routerLink]="['/notifications']"

重定向到 notifications 组件

现在我希望 index.html 中的 <app_root></app_root> 填充 notifications-component.html

首先,上面的假设对吗?

我尝试更改 notification-component.ts
中的选择器 我尝试将 <app-notifications></app-notifications> 放入 <app_root></app_root>
我尝试将 <router-outlet></router-outlet> 放入 <app_root>app.component.htmlnotifications.component.html。 (只有 app.component.html 有效。但它显示了两个 HTML。)

如果上述假设不正确,它应该如何工作?

P.S.

谢谢大家的及时回复。

我知道你所有的答案都是对的,但我只能接受一个答案。

AppComponent 应该是您应用程序的根组件,内部有 <router-outlet></router-outlet>(可能很少或仅此而已)。没有通往那里的路线,它是始终呈现的一个组件。

创建一个单独的组件处理登录(例如LoginComponent),并具有如下路由:

RouterModule.forRoot([
        { path: 'login', component: LoginComponent},
        { path: 'notifications', component: NotificationsComponent}
        { path: '', redirectTo: 'login'},
    ])

做你想做的更好的方法是这样的

  1. 为登录创建一个新组件
  2. app.component.html 中放置 <router-outlet></router-outlet>
  3. 以这种方式更改路由模块:

    RouterModule.forRoot([ { 路径:'',组件:LoginComponent}, { 路径:'notifications',组件:NotificationsComponent} ])

你的 RouterModule.forRoot 不能有 AppComponent。此组件在 main.ts.

中引导

您说您在 AppComponent 中添加了登录名 html。这是不正确的,您应该将其移至单独的组件 LoginComponent。完成此操作后,您可以更新 app.component.html:

<router-outlet></router-outlet>

显然,您可以在此处添加始终可见的额外内容,例如导航或页脚。

然后您应该将您的路线更新为:

RouterModule.forRoot([
  { path: '', component: LoginComponent},
  { path: 'notifications', component: NotificationsComponent}
]);

您的方法需要进行一些更改:

  1. <router-outlet></router-outlet> 添加到 app.component.html 文件。

  2. 创建另一个登录组件(例如LoginComponent

  3. 更新路线

       RouterModule.forRoot([
        { path: '', pathMatch: 'full', component: LoginComponent },
        { path: 'notifications', component: NotificationsComponent }
       ])],
    

*另外不建议使用home路径登录,如果未认证可以将url改为/login重新路由。

看看https://stackblitz.com/edit/angular-dfhxek.

就我而言,区分大小写是个问题。像我这样的新用户可能犯的一个错误是路径名称区分大小写。

我刚刚了解到 app.component.html 中的 <router-outlet></router-outlet> 行必须是该文件中的唯一行,因此我将所有 app.component.* 代码移至我调用的新组件'home.component.*',并在登录成功后从 'login' 路由到 'home'。这对我来说效果很好。