切换路线时。如何保持应用程序的状态? 我发现每次切换标签时都会重新初始化Angular类。
例如。 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.`;
}
}
答案 0 :(得分:8)
确实在导航时会创建新的组件实例。 您有几种方法可以保留您的价值:
这个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">