[CORD-1896] GUI become irresponsive

Change-Id: Iad4f09dbeb17e707037e277e86e678b82d06d72e
diff --git a/src/app/views/crud/crud.relations.service.ts b/src/app/views/crud/crud.relations.service.ts
index f6a7015..092dda8 100644
--- a/src/app/views/crud/crud.relations.service.ts
+++ b/src/app/views/crud/crud.relations.service.ts
@@ -23,6 +23,7 @@
 import {IXosFormCfg} from '../../core/form/form';
 import {IXosTableCfg} from '../../core/table/table';
 import {IXosConfigHelpersService} from '../../core/services/helpers/config.helpers';
+import {Subscription} from 'rxjs';
 
 interface IXosCrudRelationBaseTabData {
   model: any;
@@ -64,7 +65,7 @@
 
   public getModel (r: IXosModelRelation, id: string | number): Promise<IXosCrudRelationFormTabData> {
     const d = this.$q.defer();
-    this.XosModelStore.get(r.model, id)
+    const subscription: Subscription = this.XosModelStore.get(r.model, id)
       .subscribe(
         item => {
           this.$log.debug(`[XosCrud] Loaded manytoone relation with ${r.model} on ${r.on_field}`, item);
@@ -76,6 +77,8 @@
           };
 
           d.resolve(data);
+
+          subscription.unsubscribe();
         },
         err => d.reject
       );
@@ -84,7 +87,6 @@
 
   public getModels(r: IXosModelRelation, source_id: string | number): Promise<IXosCrudRelationTableTabData> {
     const d = this.$q.defer();
-
     this.XosModelStore.query(r.model)
       .subscribe(
         items => {
diff --git a/src/app/views/crud/crud.ts b/src/app/views/crud/crud.ts
index bcac6a9..b4434c8 100644
--- a/src/app/views/crud/crud.ts
+++ b/src/app/views/crud/crud.ts
@@ -27,6 +27,7 @@
 import {IXosCrudRelationService} from './crud.relations.service';
 import {IXosDebugService, IXosDebugStatus} from '../../core/debug/debug.service';
 import {IXosKeyboardShortcutService} from '../../core/services/keyboard-shortcut';
+import {Subscription} from 'rxjs';
 
 export interface IXosModelRelation {
   model: string;
@@ -73,6 +74,8 @@
   };
   public debugTab: boolean;
 
+  private subscription: Subscription;
+
   constructor(
     private $scope: angular.IScope,
     private $log: angular.ILogService,
@@ -109,24 +112,6 @@
       this.$scope.$apply();
     });
 
-    this.store.query(this.data.model)
-      .subscribe(
-        (event) => {
-          // NOTE Observable mess with $digest cycles, we need to schedule the expression later
-          $scope.$evalAsync(() => {
-            this.tableData = event;
-
-            // if it is a detail page for an existing model
-            if ($stateParams['id'] && $stateParams['id'] !== 'add') {
-              this.related.onetomany = _.filter($state.current.data.relations, {type: 'onetomany'});
-              this.related.manytoone = _.filter($state.current.data.relations, {type: 'manytoone'});
-              this.model = _.find(this.tableData, {id: parseInt($stateParams['id'], 10)});
-              this.getRelatedModels(this.related, this.model);
-            }
-          });
-        }
-      );
-
     // if it is a detail page
     if ($stateParams['id']) {
       this.list = false;
@@ -138,6 +123,21 @@
         const resource = this.ModelRest.getResource(endpoint);
         this.model = new resource({});
       }
+      else {
+        this.subscription = this.store.get(this.data.model, $stateParams['id'])
+          .first(val => {
+            // NOTE emit an event only if we have an object, and only the first time we have it
+            return Object.keys(val).length > 0;
+          })
+          .subscribe(res => {
+            $scope.$evalAsync(() => {
+              this.related.onetomany = _.filter($state.current.data.relations, {type: 'onetomany'});
+              this.related.manytoone = _.filter($state.current.data.relations, {type: 'manytoone'});
+              this.model = res;
+              this.getRelatedModels(this.related, this.model);
+            });
+          });
+      }
 
       this.XosKeyboardShortcut.registerKeyBinding({
         key: 'A',
@@ -195,9 +195,24 @@
       //   },
       //   description: 'Clear selected item'
       // }, 'view');
+
+      this.subscription = this.store.query(this.data.model)
+        .subscribe(
+          (event) => {
+            // NOTE Observable mess with $digest cycles, we need to schedule the expression later
+            $scope.$evalAsync(() => {
+              this.tableData = event;
+            });
+          }
+        );
     }
   }
 
+  $onDestroy() {
+    this.subscription.unsubscribe();
+    this.$log.info(`[XosCrud] Destroying component`);
+  }
+
   public iterateItems() {
     const rowCount = this.tableCfg.filteredData.length > this.tableCfg.pagination.pageSize ? this.tableCfg.pagination.pageSize : this.tableCfg.filteredData.length;
     if ((this.tableCfg.selectedRow + 1) < rowCount) {