【发布时间】:2016-02-22 04:40:12
【问题描述】:
所以,最后在获得一个大型模型以 Angular 和 typescript 进行编译之后,我得到了这个运行时错误:
10angular.js:12314 错误:[ng:cpws] 无法复制!制作副本 不支持 Window 或 Scope 实例。 http://errors.angularjs.org/1.4.1/ng/cpws
at angular.js:68
at copy (angular.js:857)
at copy (angular.js:932)
at copy (angular.js:888)
at Scope.$digest (angular.js:15666)
at Scope.$apply (angular.js:15935)
at bootstrapApply (angular.js:1624)
at Object.invoke (angular.js:4443)
at doBootstrap (angular.js:1622)
at bootstrap (angular.js:1642)
我没有更改任何“实现”,我只是重新构造了类以使用 TypeScript。在我的代码中没有任何地方可以使用 angular.copy(在整个应用程序的任何类中)。在多次将头撞在墙上之后,我偶然发现了这个问题。构造函数将 $rootScope 分配给一个局部变量(由于 TS,它现在位于原型上)。现在,这是一种旧代码,我只使用 $rootScope 的 ref 将其用作所有使用 $rootScope.broadcast(...) 的视图控制器的通用事件调度程序。当我使用标准角度样板注入它时,它曾经工作正常,我可以重构它......
/// <reference path="../../app/reference.ts" />
class UserModel {
roles:string;
activeRole:string;
errorString:string;
loginAttemptEmailValue:string;
successString:string;
static $inject = ['utils', '$rootScope','$q', '$cookies', '$http','settings', '$location'];
constructor(u,r,q,c,h,s,l) {
this.utils = u;
this.rootScope = r; // <---- the problem. comment-out this line and it works.
this.q = q;
this.cookies = c;
this.http = h;
this.settings = s;
this.location = l;
}
...
angular.module('App').service('userModel', UserModel );
但这让我担心,当我去转换我的控制器时,我会遇到同样的问题,只是注入 $scope。
所以,我的问题是,我如何使用这个 TypeScript 静态注入器模式正确注入 $scope 而不会出现这个可怕的复制错误?
我尝试创建一个类级别的静态作用域变量,但在尝试分配给静态类型时当然会出现左侧赋值错误。
更新: 这是转译的js。
var UserModel = (function () {
function UserModel(u, r, q, c, h, s, l) {
var _this = this;
this.utils = u;
this.rootScope = r;
this.q = q;
this.cookies = c;
this.http = h;
this.settings = s;
this.location = l;
}
UserModel.prototype.hasActiveRole = function (val) {
if (this.activeRole === val) {
return true;
}
return false;
};
//...other implementation...
UserModel.$inject = ['utils', '$rootScope', '$q', '$cookies', '$http', 'settings', '$location'];
return UserModel;
})();
angular.module('App').service('userModel', UserModel);
【问题讨论】:
-
澄清请求:如果您注释掉
this.rootScope = r;,那么您的应用仍然可以正常运行(减去广播)? -
是的!它是使应用程序立即出错的那一行。我可以将其注释掉,稍后在程序执行时得到一个正常的 null 错误。
-
有道理,你能分享使用
$rootScope的代码吗?你上面的作业是正确的。 -
对,我只用来广播。
this.rootScope.$broadcast('changeRole');可能是另一个广播“loggedOut”之类的。我目前正在尝试将控制器转换为 TS,看看这实际上有多大意义。
标签: javascript angularjs angularjs-scope typescript