Im using the Location service from Angular but on certain pages its page method returns an empty string which is different from windowlocationpathname Why
The difference between the page() method of the Angular Location service and window.location.pathname is likely due to how Angular handles routing.
The page() method of the Location service returns the path component of the current URL. It represents the part of the URL after the host and port, but before any query parameters or fragment identifiers. It does not include the leading slash.
On the other hand, window.location.pathname returns the path of the current URL, including the leading slash.
The reason why the page() method might return an empty string on certain pages could be because those pages are using Angular's routing feature, which allows you to define routes and views within your Angular application. When you navigate to a different route within your Angular application, the URL in the address bar might not change, but the Angular router still internally handles the routing and updates the view accordingly. In such cases, the page() method may not return the expected value.
To get the same value as window.location.pathname using the Angular Location service, you can use the path() method instead. The path() method returns the path of the current URL, including the leading slash.
Here's an example:
import { Component } from '@angular/core';
import { Location } from '@angular/common';
@Component({
selector: 'app-my-component',
template: `
<p>Location path: {{ location.path() }}</p>
<p>window.location.pathname: {{ windowLocationPath }}</p>
`
})
export class MyComponent {
windowLocationPath = window.location.pathname;
constructor(private location: Location) {}
}
In this example, location.path() and window.location.pathname would have the same value
原文地址: http://www.cveoy.top/t/topic/ilGe 著作权归作者所有。请勿转载和采集!