在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数组中。