如何在 angular 2 中创建动态路由链接?

How to create dynamic routerlinks in angular 2?

我是 angular 2 的新人,我正在尝试创建一个新闻网站,这意味着例如主页包含来自不同类别的不同文章。

所以我从 api 的滑块部分获取文章,例如 json 结果包含 link ex: '/slider/article1' , '/sport/article3'等..

当我尝试在 html 中循环结果时,路由器 link 不工作!

这是一个示例代码

Home.component.html // 假设 link 包含 '/sport'

<a [routerLink]="[item.link]">{{item.title}}</a>

Route.config.ts

export const rootRouterConfig: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
  { path: 'sport', component: SportComponent }
];

** 忘记提错误了

Uncaught (in promise): TypeError: Cannot read property 'outlets' of null

Home.component.ts

import { Component, OnInit } from '@angular/core';
import { HomeService } from '../../_services/home.service';
import { ContentInfo } from '../../_models/content';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
  providers: [HomeService]
})
export class HomeComponent implements OnInit {
  mainNewsItem: ContentInfo[];
  constructor(private _homeService: HomeService) {
    this.mainNewsItem = [];
  }
  ngOnInit() {
        // Get Main News Item
        this._homeService.getMainNewsItem()
            .subscribe(content => this.mainNewsItem = content,
            error => this._homeService = <any>error)
            ;
  }
}

我使用了 *ngif

*ngIf="mainNewsItem?.length > 0"

div 不见了,但为什么?我的意思是 mainNewsItem 包含数据 !

谢谢:)

您可以使用路由参数:

{ path: 'sport/:articleTitle', component: SportComponent },

Source: Angular doc's: route with parameter

在您的 SportComponent 中,您可以在构造函数中注入 ActivatedRoute 以接收参数:constructor(private route: ActivatedRoute)