我在通过引用将对象从 Angular 服务绑定(bind)到对象到 Angular Controller 时遇到问题。我正在我的服务中发出一些 http 请求,如以下伪代码所示:
this.object = {};
http_request -> then this.object = response
在我的 Controller 中,我有以下内容:
this.controllerObject = MyService.object
但是,当响应来自服务器时, Controller 中的值不会更新 - 仍然定义为空对象。我哪里做错了?
谢谢!
更新
好吧,我发现使用以下方法可以使其工作:
angular.copy(response,this.object)
但是为什么呢?
最佳答案
this.object = {};
http_request -> then this.object = response
当你这样做时,你会说
第一行:我将把 this.object
属性分配给一个空对象(引用位置 A)
第二行:我将把 this.object
属性分配给 response
对象(引用位置 B)
然后在你的 Controller 中
this.controllerObject = MyService.object
当您像这样初始化 Controller 时,您会说我会将 this.controllerObject
分配给 MyService.object
。此时,MyService.object
指向位置 A(因为服务中的第一行已经执行)。
然后您调用您的服务(我想您稍后会在流程中调用以下行)
http_request -> then this.object = response
此行之后 this.object
将指向位置 B,它不会更改位置 A 中的数据,因此位置仍保持空对象 => 您的controllerObject属性不是也发生变化。
关于您的更新,您可以查看angular.copy的文档。它说:
If a destination is provided, all of its elements (for arrays) or properties (for objects) are deleted and then all elements/properties from the source are copied to it.
这意味着 angular.copy 不会创建新的引用,而是会用新值更新目标位置。这就是您的更新有效的原因。
关于javascript - 通过引用将服务中对象的值绑定(bind)到 Controller 中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35646200/