2017-05-24 71 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) –