2017-05-24 70 views
0

我是新的角2,我試圖創建一個新聞網站,這意味着主頁例如包含不同類別的不同文章。如何在角度2中創建動態路由器連接?

所以我得到的,例如從API滑動部JSON結果包含鏈接前的文章:「/滑塊/第一條」,「/運動/第三條」等。

當我嘗試循環在html中的結果routerlink不起作用!

這裏是一個示例代碼

Home.component.html //可以說是鏈接中包含 '/體育'

<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" 

股利走了,但爲什麼呢?我的意思是mainNewsItem包含數據!

謝謝:)

+0

能你在盜賊身上重現你的問題?和控制檯中的錯誤是什麼 –

+0

[根據文檔](https://angular.io/docs/ts/latest/guide/router.html#!#route-def-with-parameter),你應該使用路線參數。如果你不明白,隨時問! – trichetriche

+0

錯誤 - 未被捕獲(承諾):TypeError:無法讀取屬性'outlets'爲空, –

回答

1

您可以使用路由參數:

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

Source: Angular doc's: route with parameter

在你SportComponent,你可以注入ActivatedRoute在構造函數收到的參數:constructor(private route: ActivatedRoute)

+0

即使沒有文章標題,問題也會出現我的意思是即使鏈接只是'/ sport',有人告訴我在html dom完成之前加載的路徑如此錯誤「Uncaught(在promise中):TypeError:Can not read property '零售商'的意思是。! –

+0

但感謝這將有助於下一步。 –

+0

我覺得你的'物品'在加載時還沒有設置。您可以通過向父元素添加['* ngIf =「」'指令來解決此問題。](https://angular.io/docs/ts/latest/api/common/index/NgIf-directive.html) –