切换标签/路线时如何保留表格数据?
切换路线时.如何保持应用程序的状态不变? 我观察到每次切换选项卡时Angular类都会重新初始化.
When switching routes. How to keep state of the application as it is? I observed that Angular class is reinitialize every time I switch tabs.
例如 柱塞
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.`;
}
}
在导航时会创建新的组件实例. 您可以通过多种选择来保持自己的价值:
Indeed new component instance are created when navigating. You have several options to hold your value:
- 将其存储在应用程序绑定服务中
- 将其存储在持久性存储中(localStrage/sessionStorage)
这个矮人 http://plnkr.co/edit/iEUlfrgA3mpaTKmNWRpR?p=preview实现前一个.重要的位子是
this plunker http://plnkr.co/edit/iEUlfrgA3mpaTKmNWRpR?p=preview implements the former one. Important bits are
服务(searchService.ts)
the service (searchService.ts)
export class SearchService {
searchText: string;
constructor() {
this.searchText = "Initial text";
}
}
在引导应用程序时将其绑定,以使实例可在整个应用程序中使用:
Binding it when bootstraping the app, so that the instance is available through the whole app:
bootstrap(App, [
HTTP_BINDINGS,ROUTER_BINDINGS, SearchService,
bind(LocationStrategy).toClass(HashLocationStrategy)
])
.catch(err => console.error(err));
将其注入到SearchPage组件中:(并不是因为导航时会创建一个新的组件实例,所以您不应覆盖构造函数中的值)
Injecting it in your SearchPage component: (not that you should not override the value in the constructor since a new component instance is created upon navigation)
export class SearchPage{
searchService: SearchService;
constructor(searchService: SearchService) {
this.searchService = searchService;
}
}
更新输入的服务值:
<input class="form-control" [value]="searchService.searchText"
(input)="searchService.searchText = $event.target.value">