2016-08-07 95 views
1

我有一个用TS写的Angular2应用程序,它使用Ionic进行状态和页面路由。Angular2在导航后丢失数据

粗略布局如下; type.component.html是type.component.ts的视图,它导入一个商店type.store.ts,它扩展了一个类base.store.ts

我试图将商店作为单例注入到我的应用程序,因为它只是数据库CRUD对类型的操作,并没有多大意义,并且相同的数据集将以多个组件呈现。

显示缺陷的Plunkr(只是查看存储,使用左上角后退按钮,再次查看存储...数据丢失)。 http://embed.plnkr.co/M5FO3CKQsvOSacTbkgdV/

这个错误在这里,如果我;

  1. 导航到页面,base.store和type.store的构造函数被调用,数据被初始化并显示在屏幕上。

  2. 我可以在闲暇时添加/编辑/删除数据库和组件视图,如我所期望的那样完全更新。

  3. 我甚至可以转到另一个组件,使用扩展了相同base.store(也是相同的)的不同商店进行相同定义。同样的行为,它出现了,我可以与它互动。

  4. 但是;一旦我离开了另一个页面,然后回到相同的页面,数据集是空的或没有显示在页面上;并且构造函数或加载事件不会触发。

我在想也许这是关于我的商店继承设置的方式,否则我不确定。

相关的代码:

component.html

<ion-item *ngFor="let type of types$ | async"> 
    {{type.name}} 
</ion-item> 

component.ts

@Component({ 
    templateUrl: 'build/components/types.component.html' 
}) 
export class TypesComponent {  
    private types$: Observable<Array<Type>>;  
    constructor(private navController: NavController, private typeStore: LiftTypeStore) { 
    this.types$ = this.typeStore.types$; }} 

store.ts

@Injectable() 
export class TypeStore extends BaseStore { 

    protected _subject$: Subject<Array<Type>>; 
    options; 

    constructor(protected http: Http, protected configService: ConfigService) { 
    super(http, configService); 

    this.options = { 
     collection: "types", 
     model: "Type", 
     route: "types" 
    }; 
    this.init(this.options); 
    } 

    get types$() { 
    return this._subject$.asObservable(); 
    } 

base.store.ts

export class BaseStore { 

    protected options: { 
    collection: string, 
    model: string, 
    route: string 
    }; 
    protected _subject$: Subject<Array<any>>; 
    protected dataStore: {}; 

    constructor(protected http: Http, protected configService: ConfigService) { 
    } 
    init(options) { 
    this.options = options; 
    this.dataStore = {}; 
    this.dataStore[options.collection] = []; 
    this._subject$ = <Subject<Array<any>>>new Subject(); 
    this.load(); 
    } 

    load() { 
    this.http.get(this.configService.getBaseUrl() + this.options.route).map(response => response.json()).subscribe(
     data => { 
     console.log("base store load"); 
     this.dataStore[this.options.collection] = data; 
     this._subject$.next(this.dataStore[this.options.collection]); 
     }, 
     error => console.log('Could not load', this.options.collection)); 
    } 

和app.ts

ionicBootstrap(MyApp, [ConfigService, TypeStore, LogStore]); 
+0

这看起来很奇怪。你能以某种方式创建一个Plunker与这些代码和模拟数据,所以我们可以玩吗? –

+0

@HarryNinh让它在Plunkr,同样的技术堆栈和设置中复制,http://embed.plnkr.co/M5FO3CKQsvOSacTbkgdV/ –

回答

0

韦尔普,固定它...

原来的引导期间,喷射商店App宽是造成问题。一旦我从那里移除并在Component构造函数中作为提供者添加到[providers],那么一切都很完美。

我不知道为什么会发生这种情况,因为唯一的区别应该是是商店被实例化一次,然后传递给任何需要它的人。现在每次组件时都会创建它。但是,缺陷已解决...