【问题标题】:Angular Router Child dosent renderAngular Router Child 不渲染
【发布时间】:2020-11-25 12:50:36
【问题描述】:

在我的 app.module.ts 中,我声明了一个子路由器组件。 当我想导航到这一点时,它会像预期的那样更改 url,但 html 会渲染。

import { UserComponent } from './admintiles/user/user.component';
...
{
path: 'admin', component: AdminComponent, canActivate: [AuthGuardService], resolve: {
  user: UserResolve
},
children: [
  { path: 'user', component: UserComponent, canActivate: [AuthGuardService], resolve: {
    user: UserResolve
  }, data: {roles: 'Admin'}
},
],
data: {roles: 'Admin'}

}

用户组件

    @Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.scss']
})
export class UserComponent implements OnInit {

  constructor(private route: ActivatedRoute, private http:HttpClient) { }
  user: any;

  ngOnInit(): void {
    this.route.data.subscribe((data) => { 
      this.user = data.user;
    }); 
  }

}

管理员.component.html

    <div class="tiles">
      <div class="userTile" [routerLink]="['user']">
          <div class="tileContainer">
          ...

有人能发现我的问题吗?

【问题讨论】:

    标签: angular typescript angular-router


    【解决方案1】:

    根据角度文档,当 Nesting Routes 时,您还应该包含一个

    第二个 除了 AppComponent 中的那个。

    在您的情况下,AdminComponent 是父路由,UserComponent 是子路由,它将在 AdminComponent 内呈现。要指示 Angular 您希望组件准确呈现的位置,请使用第二个 &lt;router-outlet&gt;&lt;/router-outlet&gt;

    admin.component.html

    <div class="tiles">
      <div class="userTile" [routerLink]="['user']">
        <div class="tileContainer">
          <router-outlet></router-outlet>  // UserComponent template will be rendered here 
        </div>
      </div>
    </div>
    

    还请记住,这种子路由方法不允许您一次渲染多个子路由。因此,也许您希望改进您​​的代码,以便以灵活的方式选择要呈现的子组件,并仍然应用来自 tileContainer 的样式。

    <ul class="tilesNavigation">
      <li><a routerLink="user-type-1">User type 1</a></li>
      <li><a routerLink="user-type-2">User type 2</a></li>
      <li><a routerLink="user-type-3">User type 3</a></li>
    </ul>
    <div class="tileContainer">
      <router-outlet></router-outlet>  // Child templates will be rendered here 
    </div>
    

    【讨论】:

    • 完美 - 现在 html 将在我的管理组件中呈现,但我的理解是子路由是错误的。我想展示一个完整的新网站,而不是我的管理网站的 html :)
    • 确实,当父子组件有一些连接的逻辑时,使用子路由。例如,在父产品页面 (/products) 中,您将按 id (/products/:id) 显示不同的产品。根据您的应用程序有多大,考虑将您的逻辑进一步拆分为不同的模块,而不是拥有一个独特的 app.component.ts。
    猜你喜欢
    • 2023-04-06
    • 2016-02-22
    • 2023-02-06
    • 2019-04-15
    • 2015-06-15
    • 2018-09-20
    • 2020-09-04
    • 1970-01-01
    相关资源
    最近更新 更多