在Angular中,location.path
返回当前URL的路径部分。如果location.path
返回一个空字符串,可能是因为没有设置任何路径。
要解决这个问题,你可以使用location.pathname
来代替location.path
。location.pathname
返回的是不包含查询参数和哈希值的路径部分。
下面是一个使用location.pathname
的示例代码:
import { Component } from '@angular/core';
import { Location } from '@angular/common';
@Component({
selector: 'app-example',
template: `
Path: {{ path }}
`
})
export class ExampleComponent {
path: string;
constructor(private location: Location) {}
getPath() {
this.path = this.location.pathname;
}
}
在上面的代码中,当用户点击"Get Path"按钮时,getPath
方法会将location.pathname
的值赋给path
变量。然后,路径值将显示在模板中的元素中。
请注意,要使用Location
服务,你需要首先在模块中导入CommonModule
并将其添加到imports
数组中。