Angular 2路由器重装组件

时间:2017-07-10 11:43:24

标签: angular routing

我遇到的问题似乎是Angular路由器重新加载<router-outlet></router-outlet>中的组件并导致意外结果。有没有人对如何解决这个问题有任何想法?

Plunker链接:https://plnkr.co/edit/yRCzbsxE0ftzqrDeRT69?p=preview

我如何更改它,以便在链接'one'和'two'之间交替时不重新初始化变量

1 个答案:

答案 0 :(得分:1)

您可以创建共享服务并将其注入到Parent,该服务可以包含gettersetter,您可以从那里共享数据...类似于:

import {Injectable} from '@angular/core';

@Injectable()
export class MyService {

  public data:any;

  setData(value:any) {
    this.data = value
  }

  getData():any {
    return this.data;
  }
}

并在父级中提供,例如app.module,如下所示:

@NgModule({
  declarations: [
    AppComponent,
    AnotherComponent,
    SecondComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [ MyService ], //<< add it in providers section and access it inside your component...
  bootstrap: [AppComponent]
})
export class AppModule { }