有什么方法在加载控制器前先从服务端得到某些数据?从而在controller中能保证得到值?(头大,黑线···)
定义了一个factory gData如下
angular.module('myapp', ['user'])
.factory('gData', function ($http) {
//$rootScope该怎么用????
var data = {
userInfo:{}
};
$http.get('user/getProfile', {})
.then(function (r) {
console.log(r.data); //这是console1
if(r.data.status == 1) {
data.userInfo.userId = r.data.data['user'].id;
data.userInfo.name = r.data.data['user'].name;
data.userInfo.group_id = r.data.data['user'].groups[0].id;
data.userInfo.supervisor_id = r.data.data['user'].groups[0].supervisor_id;
}
});
console.log(data);//这是console2
return data;
})
由于异步加载,console2先于1执行,所以返回的空值。
//请假条controller,user model中
.controller('AskforLeaveController', [
'$scope',
'UserService',
'$filter',
'gData',
function ($scope, UserService,$filter,gData) {
console.log(gData.userInfo); //有值
console.log(gData.userInfo.userId);//undefind
UserService.askLeaveInfo.user_id = gData.userInfo.userId; //失败,undefind!!!!how can I do
UserService.askLeaveInfo.supervisor_id = gData.userInfo.supervisor_id; //失败,undefind
//...
求解啊,该怎么处理???(哭)各种方法弄两天了
还有个问题,myapp下定义的$rootScope在user下的controller里居然也提示我undefind...
Um... like this? have a try, my first instinct, I don’t know what to do = = Program for intuition, don’t blame me if you are wrong
Um, that’s normal.
Return
promise对象
,不要返回data,直接return $http.get(xxx);
Directly when calling factory later.
Unconventional idea, I have done it before...
Give a callback method parameter in the factory. After the request is completed, call the callback and put
userInfo
in the parameter.Add a $watch and process it after there is a value (change will trigger, remember to check if it is not empty, it seems that watch will also be triggered during initialization). Remember to delete the watch after processing. It will return to
var unwatch = $watch()
的方法,直接unwatch();
and execute after calling.Send events (should not work in factory)? .
I don’t know if you know promise?
$http.get() method will return a promise. If you don’t understand promise, please google it first
The following is an idea: