2017-06-19 50 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')); 
     } 
    } 
相关问题