【问题标题】:Is there a way to get a specific string out of a route in TypeScript?有没有办法从 TypeScript 中的路由中获取特定字符串?
【发布时间】:2017-11-21 18:45:33
【问题描述】:

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

有没有办法可以阅读该链接并检查是否存在“询问”一词?

所以,

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

明确地说,我试图从浏览器中提取链接,并且没有在我的代码中定义它。

【问题讨论】:

  • 我想从浏览器中获取链接,而不是我在代码中定义的字符串
  • 你可以查询路由器获取当前路由,返回一个字符串,然后检查它是否有子字符串。
  • 好的 - 你已经尝试了什么?你使用的是什么版本的角度?请在您的问题中添加更多信息,以帮助获得良好的答案
  • 你能指定这个问题与什么角度有关吗? angular2/4 还是 angularjs?应用正确的标签

标签: angular typescript routing routes angular-routing


【解决方案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

另一种选择是将路由器直接注入组件中,这将直接允许您获取当前网址:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-09
    • 2023-04-07
    • 2015-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-07
    • 2020-04-17
    相关资源
    最近更新 更多