Is there any way to get some data from the server before loading the controller? So that the value can be guaranteed in the controller? (Big head, black line...)
A factory gData is defined as follows
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
//...
Please tell me, how to deal with it? ? ? (Crying) I’ve been doing this for two days using various methods
There is another problem. The $rootScope defined under myapp in the controller under user actually prompts me to unfind...
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: