我有一个用TS写的Angular2应用程序,它使用Ionic进行状态和页面路由。Angular2在导航后丢失数据
粗略布局如下; type.component.html是type.component.ts的视图,它导入一个商店type.store.ts,它扩展了一个类base.store.ts
我试图将商店作为单例注入到我的应用程序,因为它只是数据库CRUD对类型的操作,并没有多大意义,并且相同的数据集将以多个组件呈现。
显示缺陷的Plunkr(只是查看存储,使用左上角后退按钮,再次查看存储...数据丢失)。 http://embed.plnkr.co/M5FO3CKQsvOSacTbkgdV/
这个错误在这里,如果我;
导航到页面,base.store和type.store的构造函数被调用,数据被初始化并显示在屏幕上。
我可以在闲暇时添加/编辑/删除数据库和组件视图,如我所期望的那样完全更新。
我甚至可以转到另一个组件,使用扩展了相同base.store(也是相同的)的不同商店进行相同定义。同样的行为,它出现了,我可以与它互动。
但是;一旦我离开了另一个页面,然后回到相同的页面,数据集是空的或没有显示在页面上;并且构造函数或加载事件不会触发。
我在想也许这是关于我的商店继承设置的方式,否则我不确定。
相关的代码:
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]);
这看起来很奇怪。你能以某种方式创建一个Plunker与这些代码和模拟数据,所以我们可以玩吗? –
@HarryNinh让它在Plunkr,同样的技术堆栈和设置中复制,http://embed.plnkr.co/M5FO3CKQsvOSacTbkgdV/ –