【问题标题】:subscribing to location service of angular/common订阅 angular/common 的定位服务
【发布时间】:2017-12-06 09:41:10
【问题描述】:

我的目标是禁用浏览器窗口的后退按钮。因此,在我的组件中,我正在尝试侦听路径,因为我已经从 angular/common 导入了位置并尝试订阅它,但它似乎对我不起作用。这是我想禁用后退按钮的那个特定组件的代码 sn-p。

    import { DataService } from './../../../shared/services/data.service';
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Location } from "@angular/common";
@Component({
  selector: 'app-confirmation',
  templateUrl: './confirmation.component.html',
  styleUrls: ['./confirmation.component.scss']
})
export class ConfirmationComponent implements OnInit {
  userInput;
  customWindow;
  time;
  message: string;
  constructor(private location: Location, private dataService: DataService, private router: Router) {
     this.dataService.currentMessage
 .subscribe(message => (this.message = message));
 console.log(this.message);

this.dataService.timeSource.subscribe(time => (this.time = time));
console.log(this.time);

}

  ngOnInit(): void {
    this.customWindow = window.open("", "_blank", "");
    console.log('here');
    console.log(this.location);
 this.location.subscribe(x => console.log(x));
  }

  close () {

    console.log(this.customWindow);
   // this.customWindow.close();
 console.log('666');
 // this.router.navigate(['login']);
  }

}

【问题讨论】:

    标签: angular


    【解决方案1】:

    有一个纯 Javascript 的解决方案,不需要 Angular 方法。

    如此处所示:Disable browser back button for one page application

    您的解决方案如下所示:

    window.onpopstate = function (e) { window.history.forward(1); }
    

    但在 Angular Universal 中执行此代码时要小心。

    【讨论】:

    • 这非常适合 SPA。但是,这不是我想要的,因为我的一页(组件)只需要它。基本上,如果用户按下浏览器后退按钮(仅从该页面),那么我将尝试禁用它或将他发送到登录页面。
    • 您可以根据您的 Route via Events 设置此变量:angular.io/api/router/Router#!#events-anchor 或在 ngOnInit 中设置并在 ngOnDestroy 中重新设置
    • 嘿@Joniras,如果我试图把它放在 ngOnInit 上,那么它会在这部分 window.history.forward(1) 处给我这个错误(预期零参数但得到一个)
    • 我用这个代码 ngOnInit() 尝试了零参数: void { window.onpopstate = function(e) { window.history.forward(); }; } ngOnDestroy() { 窗口 = null; // 删除窗口; }
    • 它可以禁用它,但是如果我也尝试在地址栏中输入 url,那么它不会显示其他页面并给出此错误。 (TypeError:无法分配给对象'[object Window]'的只读属性'window')
    猜你喜欢
    • 2018-07-21
    • 2016-08-23
    • 1970-01-01
    • 2018-10-06
    • 2020-10-26
    • 2019-11-25
    • 2018-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多