溃败未加载组件

时间:2018-08-20 10:52:43

标签: angular angular-ui-router angular-routing

我试图在社交媒体公司之间导航,但是当我访问公司时,它的组件正在加载,但是当我访问社交媒体时,我得到了错误

我遇到的错误- 错误错误:未捕获(承诺):错误:无法匹配任何路由。网址段:“社交媒体” 错误:无法匹配任何路线。网址段:“社交媒体”

我将代码的详细信息放在下面

app-routing.module.ts 文件

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Routes } from '@angular/router';
import { D7socialMediaComponent } from './d7social-media/d7social-media.component';
import { CompanyComponent } from './company/company.component';

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: []
})
export class AppRoutingModule { }
export const routes: Routes = [

  {path: 'social-media' , component: D7socialMediaComponent},
   {path: 'company' , component: CompanyComponent},

];

app.component.html

 <nav>
    <a routerLink="/social-media"> Social Media </a>
    <a routerLink="/company"> Company </a>
    </nav>

    <router-outlet></router-outlet>

d7social-media.component.ts

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-d7social-media',
  templateUrl: './d7social-media.component.html',
  styleUrls: ['./d7social-media.component.css']
})
export class D7socialMediaComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

2 个答案:

答案 0 :(得分:2)

在您的app-routing.module中添加:

import { Routes, RouterModule } from '@angular/router'; 
...

    imports: [
            CommonModule,
            RouterModule.forRoot(routes),
    ]

将您的应用模块更改为:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { D7socialMediaComponent } from './d7social-media/d7social-media.component';
import { CompanyComponent } from './company/company.component';

export const routes: Routes = [

  {path: 'social-media' , component: D7socialMediaComponent},
  {path: 'company' , component: CompanyComponent},

];

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forRoot(routes) 
  ],
  declarations: []
})
export class AppRoutingModule { }

答案 1 :(得分:0)

您必须必须在 imports 数组中使用 RouterModule 声明routes,如果您使用的是lazyModule概念,则需要使用 RouterModule声明路由。 forChild(路线)

    import { NgModule } from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { RouterModule, Routes } from '@angular/router';
    import { D7socialMediaComponent } from './d7social-media/d7social-media.component';
    import { CompanyComponent } from './company/company.component';

    const appRoutes: Routes = [
         {path: 'social-media' , component: D7socialMediaComponent},
         {path: 'company' , component: CompanyComponent},
    ];

    @NgModule({
      imports: [
        CommonModule,
        RouterModule.forRoot(ppRoutes)
      ],
      declarations: []
    })
    export class AppRoutingModule { }