使用 Angular 的位置服务

Location是角度2+应用程序中提供的一项服务,它使您可以轻松地与当前的URL路径进行交互。对于大多数导航需求,角度router]是正确的解决方案,但在少数情况下,需要位置服务来影响URL,而不涉及路由器。此外,当与路由器配合执行某些操作时,定位服务可以非常方便地使用。

使用位置服务

为了访问位置服务,使用LocationStrategy和PathLocationStrategy从@angular/common导入它,将成员添加到提供者列表中,并在构造函数中注入 Location

 1// ...
 2import { Location, LocationStrategy, PathLocationStrategy } from '@angular/common';
 3
 4@Component({
 5  ...
 6  providers: [Location, {provide: LocationStrategy, useClass: PathLocationStrategy}]
 7})
 8export class AppComponent {
 9  constructor(private location: Location) { }
10
11  // ...
12}

回顾与前进

假设我们希望方法在导航中前进或后退:

1goBack() {
2  this.location.back();
3}
4
5goForward() {
6  this.location.forward();
7}

获取当前路径

您可以使用Location.Path方法获取当前路径:

1getPath() {
2  console.log(this.location.path());  
3}

位置服务+路由器

ANGLE路由器有一个Events方法,它返回一个可观测对象,我们可以订阅该对象,以便监听导航中的更改。假设我们想要监听url中的更改,如果用户位于根路径,则将isRoot成员变量设置为真:

 1isRoot: boolean;
 2
 3ngOnInit() {
 4  this.router.events.subscribe(event => {
 5    if (this.location.path() !== '') {
 6      this.isRoot = false;
 7    } else {
 8      this.isRoot = true;
 9    }
10  });
11}

<$>[注]在上面的例子中,不要忘了从@Angel/Router导入和注入路由器。<$>


定位服务有一些更有用的方法。请注意,对于所有这些方法,给定的URL首先根据应用程序的基本href值进行标准化:

  • Go:更改给定的URL并将其添加到浏览器的历史记录中。
  • replaceState:更改给定的URL,并替换历史最上面的URL。这使得如果用户返回,它将不会返回到用户所在的URL,而是返回到之前的URL。
  • isCurrentPath EqualTo:比较两个给定的路径值以查看它们是否相等。
  • Normize:获取路径并返回规范化路径。
Published At
Categories with 技术
Tagged with
comments powered by Disqus