![](/img/trans.png)
[英]how to prevent page refresh/reload on changing query string in angular 4+?
[英]How to prevent page refresh in angular 4
我想防止到處刷新頁面。
我嘗試了下面的代碼
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { CommonServices } from '../services/common.service';
@Component({
selector: 'app-review-prescription',
templateUrl: './review-prescription.component.html',
styleUrls: ['../../assets/css/prescriptionView.css'],
providers:[
CommonServices
]
})
export class ReviewPrescriptionComponent implements OnInit {
constructor(
private commonServices:CommonServices,
private router:Router
){}
ngOnInit(){
window.onbeforeunload = function(event) {
return 'By refreshing this page you may lost all data.';
}
}
}
在ngOnChanges()
、 ngOnInit()
、 ngOnDestroy()
上嘗試過這個,甚至在組件類之外(抱歉不合邏輯)但沒有任何效果?
我需要 Angular 或 JavaScript 中的解決方案,而不是 jQuery 中的解決方案。
謝謝。
嘗試以下訂閱以在頁面刷新時拋出警報窗口。 在嘗試刷新或關閉窗口之前執行一些用戶事件,例如單擊頁面。 在此處檢查工作版本
ngOnInit() {
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "\o/";
console.log("cond");
e.returnValue = confirmationMessage; // Gecko, Trident, Chrome 34+
return confirmationMessage; // Gecko, WebKit, Chrome <34
});
}
@HostListener("window:beforeunload", ["$event"]) unloadHandler(event: Event) {
event.returnValue = false;
}
解決方案取決於您為什么要阻止頁面重新加載。 如果您想阻止它,因為可能存在未保存的更改,您實際上必須阻止兩種不同的行為:
@HostListener('window:beforeunload', ['$event'])
beforeUnloadHander() {
// or directly false
this.allowRedirect;
}
I. 接口設置了 angular guard 中使用的幾個字段來檢查我們是否可以更改路由器路徑:
import { Observable } from "rxjs";
import { HostListener } from "@angular/core";
// see https://scotch.io/courses/routing-angular-2-applications/candeactivate
// implementing this interface with a component in angular you can implement a candeactivate
// guard that automatically checks if there is the canDeactivate function and
// it allows to navigate out of the route or not
export default interface LockableComponent {
allowRedirect: boolean;
canDeactivate(): boolean;
}
二、 每個組件都必須使用方法 canDeactivate 或 allowRedirect 字段(可在問題 #1 的 HostListener 中重用)實現此接口,並且必須返回一個布爾值,指示是否允許導航。
三、 創建一個路由器守衛,檢查此組件字段是否停用:
canDeactivate(
component: LockableComponent,
currentRoute: ActivatedRouteSnapshot,
currentState: RouterStateSnapshot
): Observable<boolean> | Promise<boolean> | boolean {
if (
(component.allowRedirect === false ||
(component.canDeactivate && !component.canDeactivate()))
) {
// Angular bug! The stack navigation with candeactivate guard
// messes up all the navigation stack...
// see here: https://github.com/angular/angular/issues/13586#issuecomment-402250031
this.location.go(currentState.url);
if (
window.confirm("Sure man?")
) {
return true;
} else {
return false;
}
} else {
return true;
}
}
三、 在你的 module.routing.ts 文件中設置 canDeactivate 路由器保護:
const myRoutes: Routes = [
{
path: "locked-route-path",
component: ComponentThatImplementsLockedInterface,
canDeactivate: [TheCanDeactivateGuardJustMade]
}
//...
]
你可以試試這個。
@HostListener('window:beforeunload', ['$event'])
beforeunloadHandler(event) {
alert('By refreshing this page you may lost all data.');
}
請務必將其包含在課程中。
我已經使用RouteGuard和純Javascript代碼來防止瀏覽器關閉選項卡/返回/關閉窗口。
零件:
profileForm = this.fb.group({
ClientName: ['', [Validators.required]]
});
@HostListener('window:beforeunload', ['$event']) beforeUnloadHander(event: any) {
debugger
var isFormDirty = document.getElementById('profileformStatus').innerText;
console.log(isFormDirty);
if(isFormDirty == 'true'){
return false;
}
else{
return true;
}
}
組件 HTML:
<div id="profileformStatus">{{profileForm.dirty ? true:false}}</div>
您的組件保護服務文件(可選):
import { CanDeactivate } from "@angular/router";
import { Injectable } from "@angular/core";
import { YourComponent } from "./projects/your-component";
@Injectable()
export class YourComponentCanDeactivateGuardService
implements CanDeactivate<YourComponent> {
canDeactivate(component: YourComponent): boolean {
if (component.profileForm.dirty) {
return confirm('Are you sure you want to discard your changes?');
}
return true;
}
}
你的模塊:添加上面的警衛(可選)
@NgModule({
providers: [YourComponentCanDeactivateGuardService]
})
最后
更新您的路由模塊(可選):
const routes: Routes = [
{
path: 'detail/:id',
component: YourComponent,
canDeactivate: [YourComponentCanDeactivateGuardService]
}
];
完畢。 現在它將阻止重新加載/返回導航。
之前的所有答案都包含此代碼,但我們需要添加一條語句來防止默認行為。
event.preventDefault()
@HostListener("window:beforeunload", ["$event"])
unloadHandler(event) {
event.preventDefault();
return event.returnValue = "Are you sure you want to exit?";
}
我一直在為此尋找完美的解決方案,但沒有一個是完美的。
我為此創建了一個解決方案,您可以在此處查看完整代碼。 防止重新加載而不保存
代碼示例: https://github.com/mukeshsalaria01/angular-show-alert-on-page-reload-without-saving-example
為此,您應該創建一個 Guard。
在您的路由配置文件中:
const routes: Routes = [
{
path: '',
redirectTo: '/homePage',
pathMatch: 'full'
},
{
path: 'accueil',
component: AccueilComponent,
canDeactivate: [GuardName]
}]
通過這樣做,您正在對選定的組件進行警戒
更多信息在這里
在你的保護下:
@Injectable()
export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {
canDeactivate(component: CanComponentDeactivate) {
return true/false;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.