最简单的Angular Route hello world场景都跑不通的一个原因

167 阅读1分钟

我有一个最简单的app Component:

@Component({
  selector: "app-root",
  template: `
  <div cxFocuses>Painful</div>
  <a href="/custom2">Click me</a>
  `
})
export class AppComponent {

}

我期望点击了Click Me这个标签之后,能跳转到相对路径/custom2.

在app.module.js里,定义一个route数组:

const CUSTOM_ROUTES: Routes = [
  { path: "custom2", component: RouteDemoComponent }
];

Routes是一个type alias,相当于Route[]:

而Route是一个interface:

angular.io/api/router/…

我将RouterModule.forRoot返回的Module放到app.module.ts的imports区域之后:

浏览器访问localhost:4200/custom2, 发现没有跳转到期望的Component里去。

经过检查,发现是因为我的application template里,缺少了router-outlet标签的定义:

加上之后,问题解决:

更多Jerry的原创文章,尽在:“汪子熙”: