Angular 2 — 在不重新加载这些页面通用的组件的情况下浏览网页

Angular 2 — navigate through web pages without reloading a component that is common for those pages

在这里您可以找到一个示例应用程序: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 {

}

第 1 节第 2 页几乎相同:

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);

    }

}

放上我打开该版块第一页的案例。有没有办法在不重新加载计数器的情况下导航到同一部分的第二页?我想为此类导航问题找到一个通用的解决方案——它可能不是计数器组件,而是侧边栏导航或部分标题或其他东西。

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

是的,完全可以编写一个可以处理多个路由的组件,而无需每次都重建组件。

如果您创建一个组件来处理所有页面,如以下路由所定义:

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

您可以订阅路由参数 "page" 并在您的组件中处理页面更改。这样可以防止Angular2每次都重构页面Component。

@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 组件只会在你离开整个部分时被销毁。

您还可以在我们的博客中阅读更多相关信息 Post Angular 2 by Example

有一个模块 ng2-cache 可以让您将组件缓存到本地存储中,并提供缓存规则。我认为它应该可以满足您的需求。