Angular 2——浏览网页时不需要重新加载那些页面中常见的组件



你可以在这里找到一个示例应用程序:http://ivan-khludov.com/

这是根组件:

import { Component } from '@angular/core';
@Component({
  selector: 'root',
  template: `
  <h1>My Dummy Angular App</h1>
  <router-outlet></router-outlet>
  <nav>
    <a routerLink="/section-1/1" routerLinkActive="active">Section 1 - Page 1</a>
    <span>||</span>
    <a routerLink="/section-1/2" routerLinkActive="active">Section 1 - Page 2</a>
    <span>||</span>
    <a routerLink="/section-2/1" routerLinkActive="active">Section 2 - Page 1</a>
    <span>||</span>
    <a routerLink="/section-2/2" routerLinkActive="active">Section 2 - Page 2</a>
  </nav>
  `
})
export class AppWrapper {
}

第1页第1节的组件:

import { Component } from '@angular/core';
@Component({
  selector: 'secapagea',
  template: `
  <h2>Section 1 - Page 1</h2>
  <countera></countera>
  `
})
export class Section1Page1 {
}

第二页的第一部分也是一样:

import { Component } from '@angular/core';
@Component({
  selector: 'secapageb',
  template: `
  <h2>Section 1 - Page 2</h2>
  <countera></countera>
  `
})
export class Section1Page2 {
}

计数器组件:

import { Component } from '@angular/core';
@Component({
  selector: 'countera',
  template: `
  <div>Seconds elapsed: {{this.count}}</div>
  `
})
export class Section1Counter {
    count: number;
    constructor() {
        this.count = 0;
        setInterval(() => {
            this.count ++;
        }, 1000);
    }
}

假设我打开了section的第一页。是否有一种方法可以导航到同一部分的第二页而无需重新加载计数器?我想找到这样的导航问题的一般解决方案-它可能不是一个计数器组件,但侧边栏导航或节标题或其他东西。

是的,完全有可能编写一个可以处理多个路由的组件,而不必每次都重新构建该组件。

如果你创建了一个组件,该组件按照以下路由定义一起处理所有页面:

const routes: Routes = [
  { path: 'section-1/:page', component: Section1PageX }
];

你可以订阅路由参数"page",并在组件中处理页面更改。这可以防止Angular2每次都重新构建页面组件。

@Component({
  selector: 'secapagea',
  template: `
  <h2>Section 1 - Page {{page}}</h2>
  <countera></countera>
  `
})
export Section1PageX {
  private page: string;
  constructor(private route: ActivatedRoute) {}
  ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
       this.page = params['page'];
       //handle the page change
    });  
  }
  ngOnDestroy() {
    //unsubscribe when you leave the section
    this.sub.unsubscribe();
  }
}

所以你的Section1Counter组件只有在你离开整个section时才会被销毁。

你也可以在我们的博客文章Angular 2 by Example

中了解更多。

如果正确理解了这个问题,我认为您应该简单地将Section1Counter组件放在AppWrapper组件模板中,并将其从SectionxPagey组件中删除。通过这种方式,您将使用路由器出口来显示页面,而Section1Counter将保持相同的实例。我希望这对你有帮助

有一个模块ng2-cache,它允许你将组件缓存到本地存储,并为缓存提供规则。

相关内容

最新更新