2017-06-19 96 views
-1

說我有一條路線是http://www.stackoverflow.com/questions/ask有沒有辦法在TypeScript中從路由中獲取特定的字符串?

有沒有一種方法可以讀取該鏈接並檢查單詞「ask」是否存在?

所以,

If(link.contains["ask"]) { 
    containsAsk = true; 
} 

要清楚,我想拉從瀏覽器中的鏈接,沒有它我的代碼中定義。

+0

的可能的複製[如何檢查是否一個字符串包含JavaScript中的子字符串?](https://stackoverflow.com/questions/1789945/how-to-check-whether-a-string-contains-a-substring-in-javascript) –

+0

我想要得到鏈接,而不是我在代碼 – CodyCS

+0

中定義的字符串,您可以查詢路由器以獲取當前路由ich會返回一個字符串,然後檢查它是否有子字符串。 –

回答

1

在angular2/4中,您可以向組件注入一個ActivatedRoute的實例,將其轉換爲字符串toString()並檢查它的值。例如

@Component() 
export class TestComponent{ 
    constructor(private _route: ActivatedRoute){ 
    let link = _route.toString(); 
    console.log(link.contains('ask')); 
    } 
} 

注意,此方法將返回一個字符串形式Route(url:'${url}', path:'${matched}')

如果你想穿越了組成該鏈路的奇異元素,你可以使用parent屬性向上導航到根該實例。在the following link

另一種選擇

更多信息將直接注入路由器到組件,你會直接讓你得到當前的URL:

@Component() 
    export class TestComponent{ 
     constructor(private _router: Router){ 
     let link = _router.url(); 
     console.log(link.contains('ask')); 
     } 
    } 
相關問題