这是更好的数据共享方式,将数据附加到窗口或以角度进行服务

时间:2018-01-24 17:33:45

标签: javascript angular angular2-services angular-services

标题可能不是直截了当的,但我想在此详细解释我的疑问。

目标是找出以角度Js

存储和共享数据的最佳方式

第一种方法

将数据存储为窗口对象,如

window.myVar ='someValue'

并访问应用程序中的任何位置

第二种方法是制作服务并共享数据

   @Injectable()
export class commonDataService{

  constructor() { }

  dataService = {};

  setItem(id, val) {
    this.dataService[id] = val;
  }

  getItem(id) {
    return (this.dataService[id]);
  }

  deleteItem(id) {
    if (this.dataService[id]) {
      delete (this.dataService[id]);
    }
  }

  deleteAll() {
    // delete all properties of this item
    for (const property in this.dataService) {
      if (this.dataService[property]) {
        delete this.dataService[property];
      }

    }
  }

}

现在注入此服务并使用get和set Across application

继续获取和更新数据

在这两种方法中哪一个更好,或者在角度或javascript中有任何其他方法。

当然数据安全明智的服务作为任何人都可以看到的窗口对象更好

这两种方法的优点和缺点是什么? 1.记忆消耗明智 2.任何内存泄漏都不合适 3.随着应用程序的增长,任何其他性能影响

1 个答案:

答案 0 :(得分:1)

集中服务将是最佳选择。事实上,对于大规模应用程序,我强烈推荐使用可以帮助维护应用程序状态的Store的ngRx。或者,对于更简单的用例,您可以实现利用Subjects和Observables的集中服务。

例如。

@Injectable()
export class CentralService {
  masterData$: BehaviorSubject<any[]> = new BehaviorSubject<any[]>([1,2,3]);

  updateData(newData: number[]): void {
    this.masterData$.next(newData);
  }
}
相关问题