【发布时间】:2016-11-14 22:59:05
【问题描述】:
祝大家早安!
我正在开发一个网络应用,使用typescript和angular 1.5;
我创建了一个指令,它的主要目标是监视用户是否登录,并隐藏/显示相应的元素。
这是链接功能 代码:
interface ShowAuthedScope extends ng.IScope{
User: UserService,
_$log: ng.ILogService
}
function ShowAuthedDirective(User:UserService, $log:ng.ILogService) {
'ngInject';
return {
restrict: 'A',
link: function (scope, element, attrs) {
scope.User = User;
scope._$log = $log;
scope.$watch('User.current', function (val) {
scope._$log.log('updated!:', val);
})
}
}
}
我的案例的模型是当前用户,设置或取消设置取决于他是否登录。
这是 UserService 的剪辑代码:
interface UserInterface {
current:GoogleUser;
signIn(options?:SignInOptions):Promise<any>;
signOut():Promise<void>;
}
class UserService implements UserInterface {
public current:GoogleUser;
private _GoogleAuth:GoogleAuthService;
private _AppConstants;
constructor(GoogleAuth:GoogleAuthService, AppConstants) {
'ngInject';
this._GoogleAuth = GoogleAuth;
this._AppConstants = AppConstants;
this.current = null;
}
public signIn(options?:SignInOptions) {
let promise:Promise<any>;
let _options:SignInOptions = options || {};
_options.app_package_name = this._AppConstants.appPackageName;
if (this.current) {
promise = this.current.signIn(_options);
} else {
promise = this._GoogleAuth.signIn(_options);
}
promise = promise.then((googleUser:GoogleUser) => this.current = googleUser);
return promise;
}
public signOut() {
this.current = null;
return this._GoogleAuth.signOut();
}
}
$watch里面的函数在初始化后只被触发一次;
另外请注意,我已经尝试将 true 作为 $watch 函数的第三个参数传递
希望得到您的帮助!谢谢!
【问题讨论】:
-
听起来很可疑。要么在摘要循环之外调用
signIn和signOut,要么不调用它们,或者在同一摘要循环迭代中依次调用它们,这样User.current就不会改变。 -
或
_GoogleAuth.signIn解析为null。 -
基本上我通过控制台测试它:我得到服务实例 - var service = angular.element(document).injector().get('User');然后调用 signIn();和 signOut() 方法,并确保每次电流发生变化。
标签: javascript angularjs typescript angularjs-scope