javascript - 在 Angular 中使用 window.location.pathname.split()

标签 javascript angular

我正在使用这个 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/

相关文章:

javascript - Polymer - Vaadin 日期选择器; Vaadin 网格 : How to change date format?

angular - 根据浏览器语言设置 Angular LOCALE_ID

javascript - 将 JSON 存储到本地存储不起作用

javascript - Ngrx store dispatch 不接受字符串作为参数

javascript - 如何在提交前删除属性?

javascript - 检查数组元素的第一个字符

javascript - AngularJS 错误注入(inject)模块

javascript - Sync-gateway 返回此错误 401 Login required 是什么意思?

javascript - ngx下拉列表获取选定值

angular - 禁用 react 形式的输入字段