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

Is there a way to get a specific string out of a route in TypeScript?

假设我有一条路线 http://www.whosebug.com/questions/ask

有没有办法让我通读 link 并检查 "ask" 一词是否存在?

所以,

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

需要说明的是,我正在尝试从浏览器中提取 link,并且没有在我的代码中定义它。

在 angular2/4 中,您可以将 ActivatedRoute 的实例注入到组件中,使用 toString() 将其转换为字符串并检查它的值。例如

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

请注意,此方法将 return 一个具有 Route(url:'${url}', path:'${matched}')

形式的字符串

如果您想遍历构成 link 的单个元素,您可以使用实例的父属性向上导航到根。

更多信息见the following link

另一种选择是直接将 Router 注入到组件中,这将直接让您获得当前 url:

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