我正在使用这个 window.location.pathname.split() 来分割路径名,以便从此网址获取特定的 id:基本上我正在尝试获取/image/1 “/image/”后面的 id。我知道这很简单,而且我已经很接近了,但我似乎无法理解它。我用了两种方法都没有成功。
http://localhost:4200/image/1;id=1;catergory=testing .
(3) ["/image/1", "id=1", "catergory=testing"]
0
:
"/image/1"
1
:
"id=1"
2
:
"catergory=testing"
length
:
3
_proto_
:
Array(0)
(3) ["", "image", "1;id=1;catergory=testing"]
0
:
""
1
:
"image"
2
:
"1;id=1;catergory=testing"
length
:
3
_proto_
:
Array(0)
this.route.params.subscribe(response => {
let path = window.location.pathname.split('/');
let path1 = window.location.pathname.split(';')
const id = path[0]
console.log("Path",path)
console.log("Path",path1)
console.log("id", id)
最佳答案
这是一种可能的解决方案:
window.location.pathname.split(";")[0].split("/").pop()
说明:
window.location.pathname.split(";")
将返回:
["http://localhost:4200/image/1", "id=1", "catergory=testing"]
用[0]获取数组中的第一项,并用“/”分割:
window.location.pathname.split(";")[0].split("/")
它会返回
["http:", "", "localhost:4200", "image", "1"]
使用 pop() 或您想要的方式获取最后一个元素。
但正如 nanabyte 上面所说,使用 Angular 路由器是实现此目的的首选方法。
关于javascript - 在 Angular 中使用 window.location.pathname.split(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49703812/