简体   繁体   English

获取 angular 中的动态路径 slug 2+

[英]Get dynamical path slug in angular 2+

How do I Get router path slug in angular 2+如何在 angular 2+ 中获取路由器路径 slug

For example: So when I enter to this route: mysite.com/posts/post/15 I want to see in console.log /posts/post/:id例如:所以当我进入这条路线时:mysite.com/posts/post/15 我想在console.log /posts/post/:id 中看到

You can use regular javascript for that (inspect the window.location object attributes):您可以为此使用常规 javascript (检查window.location object 属性):

// e.g. url => https://www.w3schools.com/js/tryit.asp?filename=tryjs_loc_href

// href is the complete url
const url = window.location.href

// hostname is www.w3schools.com
const hostName = window.location.hostname;

// protocol is https
const protocol = window.location.protocol;

// the "+ 3" at the end is to compensate for "://"
const startIndex = hostname.length + protocol.length + 3;

// prints js/tryit.asp?filename=tryjs_loc_href to console
console.log(href.substring(startIndex));

You can get more info about window.location object here .您可以在此处获取有关window.location object 的更多信息。

I found this solution.我找到了这个解决方案。 I splitted route and check these splitted items on numbers, then replace them with ':id'.我拆分路线并检查数字上的这些拆分项目,然后用':id'替换它们。 I used this function for checking numbers:我用这个 function 来检查数字:

hasNumber(myString) {
 return /\d/.test(myString);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM