typescript - Angular 2 : How to Prevent my data and html view by not reloading component on browser back navigation

标签 typescript angular single-page-application angular2-routing

我的申请中有两条路线
1)/home -- HomeComponent -- Home.html



    export class HomeComponent implements OnInit, CanReuse,OnReuse, OnActivate, OnDeactivate{
    ...
       constructor(private showHomeLogo:boolean;private showLogoutButton : boolean){
        console.log("Home page Constrcutor called");
       }
       ngOnit(){
         //after some service call for user authentication
         console.log("Home page ngOnInit called");
         this.showLogoutButton  = true;
         this.showHomeLogo = true;
       }
    routerCanReuse(nextInstruction: ComponentInstruction,
        prevInstruction: ComponentInstruction): boolean {
        console.log('routerCanReuse');
        return true;
      }
      routerOnReuse(nextInstruction: ComponentInstruction,
        prevInstruction: ComponentInstruction): void {
        console.log('route on reuse');
      }
      routerOnActivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any {
        console.log("route activated");
      }
      routerOnDeActivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any {
        console.log("route Deactivated");
      }
    }

2)/users -- UserComponent -- Users.html



    export class UserComponent{
    ...
       constructor(){
         console.log("Userpage Constrcutor called");
       }
       navToBack(){
        //navigation to back page
        window.history.back();
        //also tried the following
       //window.history.go("-1");
        //location.back(); //when I import Location from Angular/common
       //router.navigate(['home'])
      }
    }

当我点击后退按钮时,我可以回到主页。
但是该组件正在重新加载它的构造函数和 ngOnit,我正在使用它失去以前的选择以显示或隐藏 html 上的一些按钮。

我正在使用 Angular 2 rc1 路由器。

我需要返回到与之前相同的 html 状态的主页。即不重新加载组件。

这意味着我所有的选择和输入条目都应该保留在主页中。

我怀疑这是因为我的 HomeComponent 在每次导航到这条路线时都会重新加载,导致我的 html 页面进入初始状态。

请帮忙。

最佳答案

您需要从 ngOnInit() 中删除您的服务函数,并将它们放在它之外的函数中,因为这会在每次导致加载时调用您的服务。

然后通过检查您的值是否为空来检查内容是否需要重新加载。

只是不要让 ngOnInit() 总是调用您的服务。

关于typescript - Angular 2 : How to Prevent my data and html view by not reloading component on browser back navigation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38108714/

相关文章:

angular - Ionic 2 中的页面过渡动画

node.js - Angular 构建 - 找不到模块 : Error: Can't resolve 'console'

angular - 如何更改表中值的格式?

python - 单页应用程序的 ReactJS 服务器端渲染

typescript - 使用镜头和遍历获取部分对象并返回 "filled in"对象的函数式编程/光学概念?

javascript - Angular Universal 和浏览器功能检查

javascript - 错误: Uncaught (in promise): Error: Template parse errors: 'app-ques-navbar' is not a known element:

angular - 当数据源可观察时,MatSort 不适用于 Angular Material Table

c# - Blazor onclick 事件从循环中传入计数器

java - 如何使用servlets和jsp做一个SPA?