加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular 2:routerLink无法解析

发布时间:2020-12-17 17:01:20 所属栏目:安全 来源:网络整理
导读:角度版本:2.1.0 路由器版本:3.1.0 我正在学习Angular 2中的路由,并且在单击链接时自定义段不会附加到URL,也不会加载组件. 手动在段中输入地址栏确实有效,组件加载到 router-outlet / router-outlet但不是这样,我希望它按预期工作 – 通过单击routerLink指
>角度版本:2.1.0
>路由器版本:3.1.0

我正在学习Angular 2中的路由,并且在单击链接时自定义段不会附加到URL,也不会加载组件.

手动在段中输入地址栏确实有效,组件加载到< router-outlet>< / router-outlet>但不是这样,我希望它按预期工作 – 通过单击routerLink指令内的链接.

我跟着路由器documentation并且仍然有不良结果.

这是一个非常相似的question,但是到目前为止还找不到对我有用的解决方案.

我遇到的两个常见解决方案是:

>拼错’routerLink’,区分大小写
>没有< base href ='/'>在index.html的顶部

Chrome中的控制台窗口也没有错误

所以在继续之前我只想取消明显的解决方案.

这是我为配置自定义路由器所做的工作:

1.配置自定义路由(routes.ts)

import { Routes,RouterModule } from '@angular/router';
import { RecipesComponent } from './recipes/recipes.component';
import { ShoppingListComponent } from './shopping-list/shopping-list.component';

//TODO Fix routing bug (not switching on click or displaying in URL)
export const APP_ROUTES: Routes = [
    {path: '',redirectTo: 'recipes',pathMatch: 'full'},{path: 'recipes',component: RecipesComponent},{path: 'shopping-list',component: ShoppingListComponent}
];

/*Set routing up for root of app*/
export const routing = RouterModule.forRoot(APP_ROUTES);

2.全球导入路线(app.module.ts)

import { routing } from './routes';//Custom routes file

    @NgModule({                     
      // Declarations removed for bravity
      imports: [
        BrowserModule,FormsModule,HttpModule,routing
      ],providers: [ShoppingListService],bootstrap: [AppComponent,]
    })
    export class AppModule { }

3.提供RouterOutlet指令(app.component.html)

<rb-header></rb-header>
<div class="container">
  <router-outlet></router-outlet>
</div>

4.使用静态段实现routerLink(header.component.html)

<ul class="nav navbar-nav">
    <li><a routerLink="/recipes">Recipes</a></li>
    <li><a routerLink="/shopping-list">Shopping List</a></li>
</ul>

路由器documentation表示使用routerLink用于静态段,[routerLink]用于使用params传递.我尝试了两种方法,但它们仍然会产生相同的结果.

解决方法

我终于解决了这个问题.

原因是什么?

我的component.html中有一个不相关的bug,其中有一个属性将字符串分配给’name’的未知属性 – Angular 2在设置’recipe’对象之前编译了字符串插值.

<h4 class="list-group-item-heading">{{recipe.name}}</h4>

固定

我使用了safe navigaton operator来防御属性路径中的空值:

<h4 class="list-group-item-heading">{{recipe?.name}}</h4>

结论

路由中没有错误 – 这是我的应用程序的另一部分中的一个错误,它被chrome-dev工具捕获,然后需要修复以便继续编译应用程序

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读