如何在切换时保持表单数据tabs/routes?

How to keep form data when switching tabs/routes?

切换路线时。如何保持应用程序的状态? 我观察到 Angular class 每次切换标签时都会重新初始化。

例如。 Plunker

import {Component, View, CORE_DIRECTIVES} from 'angular2/angular2'
@Component({
})
@View({
  template: `
 <input class="form-control" [value]="test"> </input>
 <br>
 {{test}}
`
})
export class SearchPage{
    test = `Type something here go to inventory tab and comeback to search tab. Typed data will gone.
    I observed that Angular class is reinitialize every time I switch tabs.`;
    }
}

确实在导航时创建了新的组件实例。 您有多种选择来保持您的价值:

  • 将其存储在应用绑定服务中
  • 将其存储在持久存储中(localStrage / sessionStorage)

这个 plunker http://plnkr.co/edit/iEUlfrgA3mpaTKmNWRpR?p=preview 实现了前一个。重要的位是

服务 (searchService.ts)

export class SearchService {
  searchText: string;
  constructor() {
    this.searchText = "Initial text";
  }
}

在引导应用程序时绑定它,以便实例在整个应用程序中可用:

bootstrap(App, [
  HTTP_BINDINGS,ROUTER_BINDINGS, SearchService,
  bind(LocationStrategy).toClass(HashLocationStrategy)
  ])
  .catch(err => console.error(err));

将其注入到您的 SearchPage 组件中:(请注意,您不应覆盖构造函数中的值,因为在导航时会创建一个新的组件实例)

export class SearchPage{
  searchService: SearchService;
  
  constructor(searchService: SearchService) {
    this.searchService = searchService;
  }

}

更新输入的服务值:

<input class="form-control" [value]="searchService.searchText"
 (input)="searchService.searchText = $event.target.value">