services.factory('profilFactory',['$q','$http',function($q,$http){
var factory2 =
{
profils : {},
getProfils : function(){
$dfd = $q.defer();
$http.get('data.json')
.success(function(data,status){
this.profils = data.profil;
$dfd.resolve(this.profils);
})
.error(function(data,status) {
$dfd.reject('erreur recuperation des profils');
});
return $dfd.promise;
},
getProfil : function(idProfil){
var profil={};
var profils = {};
factory2.getProfils().then(function(data){
profils= data;
console.log(profils);//all right until here profils has values
});
console.log(profils);// now profils is empty :\ and the foreach will not execute
angular.forEach(profils, function(value, key){
if(value.id == idProfil){
profil= value;
}
});
return profil;
}
};
return factory2;
}]);
答案 0 :(得分:0)
您的console.log语句不在回调中。这就是问题所在。您需要在回调中使用console.log,或者在更改时使用观察程序进行更新。为了将来参考,您应该始终在此复制并粘贴代码。
答案 1 :(得分:0)
要回答您的问题,“为什么变量在工厂中为空”,这是因为您在尚未从服务器加载数据的位置使用services.factory('profilFactory',['$q','$http',function($q,$http){
var factory2 =
{
profils : {},
getProfils : function(){
$dfd = $q.defer();
$http.get('data.json')
.success(function(data,status){
this.profils = data.profil;
$dfd.resolve(this.profils);
})
.error(function(data,status) {
$dfd.reject('erreur recuperation des profils');
});
return $dfd.promise;
},
getProfil : function(idProfil){
var profil={};
var profils = {};
// Run a function to get data, "THEN" we run a function to process the data:
factory2.getProfils().then(function(data){
// Data has now been loaded so we can process it and return it.
profils = data;
angular.forEach(profils, function(value, key){
if(value.id == idProfil){
profil= value;
}
});
return profil;
});
console.log(profils); // This is EMPTY because it runs immediately after
// the factory2.getProfils() function which may need several seconds to
// load data. That's why "profils" is empty. The data hasn't loaded at
// this point.
//
// No data will be available at this level of the code. Don't try to access
// "profils" here! Only in your .then() function above.
}
};
return factory2;
}]);
语句。要了解更多信息,请访问Google:“angularjs http get promises”
import java.util.Scanner;
import java.util.regex.Pattern;
public class TestClass {
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
boolean containsDigit = Pattern.compile("[0-9]").matcher(input).find();
boolean containsNonDigitNonPeriod =
Pattern.compile("[!--/:-~]").matcher(input).find();
int numberOfPeriods = input.replaceAll("[^.]", "").length();
if (containsDigit && !containsNonDigitNonPeriod)
{
if (numberOfPeriods > 1)
System.out.println("A string has been input.");
else if (numberOfPeriods == 1)
System.out.println("A float has been input.");
else
System.out.println("An integer has been input.");
}
else
System.out.println("A string has been input.");
scanner.close();
}
}