【问题标题】:How to keep form data when switching tabs/routes?切换选项卡/路由时如何保留表单数据?
【发布时间】:2015-12-21 16:54:21
【问题描述】:

切换路线时。如何保持应用程序的状态不变? 我观察到每次切换标签时 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.`;
    }
}

【问题讨论】:

    标签: angular


    【解决方案1】:

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

    • 将其存储在应用绑定服务中
    • 将其存储在持久存储中 (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">
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-29
      • 1970-01-01
      • 2011-05-21
      • 2021-12-27
      • 1970-01-01
      相关资源
      最近更新 更多