导航到上一页/网址(如果存在)

时间:2018-01-13 04:48:11

标签: angular

我目前正在使用Location来浏览我的应用程序。 这意味着在角落中显示一个后退按钮,单击该按钮时会触发goBack()函数。

@Component({
  selector: 'app-main',
  templateUrl: './main.component.html',
  styleUrls: ['./main.component.css']
})
export class MainComponent {
  constructor(
    public location: Location
  ) {}

  goBack() {
    this.location.back();
  }
}

有时虽然没有上一页,但是给用户留下了印象,显示按钮的时间。

如何确定是否没有页面?

这样我就可以隐藏当前显示的按钮。

我正在使用Angular 5

1 个答案:

答案 0 :(得分:1)

订阅服务中的路由器事件,并在组件中注入该服务。当组件激活时,从服务中获取前一个URL。

import { Injectable } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';

@Injectable()
export class RouterService {
    previousUrl: string = 'none';
    constructor(
        private router: Router
      ) {
        this.router.events
          .subscribe((event) => {
            if (event instanceof NavigationEnd) {
              this.previousUrl = event.url;
            }
          });
      }
}

import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'app-some',
    template: `<span *ngIf="prevUrl !== 'none'>Back</span>`,
    styles: [``]
})
export class SomeComponent implements OnInit {
    prevUrl;
    constructor(private routerService: RouterService) { 
        this.prevUrl == routerService.previousUrl;
    }

    ngOnInit() { }
}