2016-09-09 17 views
0

我有一個組件(如下所示),它實現了相當的教科書訂閱路由參數。從同一頁面上的兩個組件訪問路由參數

export class tutorialComponent implements OnInit, OnDestroy { 
    private sub: Subscription; 
    public chapter: string; 

    constructor(private route: ActivatedRoute) {} 

    ngOnInit() { 
    this.sub = this.route.params.subscribe(params => { 
     this.chapter = params['id']; 
    }); 
    } 

    ngOnDestroy() { 
    this.sub.unsubscribe(); 
    } 
} 

然而,路線:http://localhost:3000/tutorial/chapter/0如果我從瀏覽器中運行ng.probe($0).componentInstance(在選擇教程CMP),那麼我可以看到章=未定義 - 爲什麼?

此外,如果我使用this.chapter = +params['id'];,那麼chapter = NaN

更新:

我有兩個組成部分,一個父(教程)和兒童(章)的組成部分。兩者相同:

ngOnInit() { 
    this.sub = this.route.params.subscribe(params => { 
     this.chapter = params['id']; 
    }); 
    } 

但是,子組件正確顯示chapter

回答

0

每個文件建議的方法是使用route.snapshot:

this.validationCode = route.snapshot.params['id']; 

這是從工作程序......

+0

但是我想更新... –

+0

我不明白? –

+0

@JohnBaird - 他意思是這個網址是動態的,他需要一個觀察者 – mrgoos

0

您需要params['id'];轉換爲數字是這樣的:

this.chapter = +params['id'];

+0

恐怕不能解決問題,作爲一個字符串,我得到'undefined'作爲一個數字(即你的解決方案)我得到'NaN' –

+0

所以這意味着什麼都不傳遞給路由參數'id'。如果你可以在plnkr中分享一段代碼,那可能會有所幫助。 – mrgoos

+0

那麼孩子的工作和家長不工作?奇怪的。我想讓你嘗試'this.route.parent.params ...',這樣你就可以從所有父母那裏得到params,或許你應該嘗試一下以防萬一。 – mrgoos

相關問題