有没有办法在TypeScript中从路由中获取特定字符串?

时间:2017-06-19 13:52:15

标签: angular typescript routing routes angular-routing

假设我的路线为http://www.stackoverflow.com/questions/ask

有没有办法可以通读该链接,并查看是否单词"问"在那儿?

所以,

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

要清楚,我试图从浏览器中提取链接,并且没有在我的代码中定义它。

1 个答案:

答案 0 :(得分:2)

In angular2/4 you could inject into a component an instance of ActivatedRoute, transform it to string with toString() and check the value of it. For example

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

Note that this method will return a string with the form Route(url:'${url}', path:'${matched}')

If you want to traverse the singular elements that compose that link, you can navigate up to the root using the parent attribute of the instance.

More info in the following link

Another option would be to directly inject the Router into the component, what will directly allow you to get the current url:

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