这是我的代码:
var updateScreen = function() {
$http.get("http://localhost:5000").then(function(response){
$scope.numSerie = response.data.refDetail.Num_Serie;
$http.get("data/tempsgammes.json").then(function(res){
$scope.time = res.data[$scope.numSerie].temps;
console.log($scope.time)
})
console.log($scope.time)
}
第一个$ http.get(&#34; http://localhost:5000&#34;)返回我在其余代码中使用的详细信息列表,我们感兴趣的是变量 numSerie < /强>
根据 numSerie 的值,将执行另一个$ http.get(&#34; data / tempsgammes.json&#34;)以提取时间来自JSON文件的 numSerie 。
问题是我无法在$ http的第二次调用中访问 $ scope.time 。第一个console.log()给了我想要的结果,但第二个未定义。
任何人都可以帮助我吗?
答案 0 :(得分:2)
编辑:正在调用console.log($ scope.time)2次。你看到第一个给出了正确的价值而第二个没有给出正确的价值。 这是因为&#34;然后&#34;的异步行为。它不直观,但第二个console.log($ scope.time)在&#34;然后&#34;之前被调用。已经完成,这就是为什么它显示&#34; undefined&#34;。
编辑2 :尝试以下操作来探测异步操作的执行顺序
public class SqliteDBManager extends SQLiteOpenHelper{
private static final int DB_VERSION = 1;
private static final String DB_NAME = "baby_diary.db"
private static final String TBL_BABIES = "babies";
private static final String BABIES_BABY_ID = "baby_id";
private static final String BABIES_NAME = "name";
private static final String BABIES_DOB = "dob";
private static final String BABIES_GENDER = "gender";
private static final String BABIES_WEIGHT = "weight";
private static final String BABIES_HEIGHT = "height";
private static final String BABIES_THEME = "theme";
public SqliteDBManager(Context context, String name, SQLiteDatabase.CursorFactory factory, int version, DatabaseErrorHandler errorHandler) {
super(context, DB_NAME, factory, DB_VERSION, errorHandler);
}
public void onCreate(SQLiteDatabase db) {
String CREATE_TBL_BABIES = "CREATE TABLE " + TBL_BABIES + "( " +
BABIES_BABY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
BABIES_NAME + " TEXT, " +
BABIES_DOB + " TEXT, " +
BABIES_GENDER + " TEXT, " +
BABIES_WEIGHT + " REAL, " +
BABIES_HEIGHT + " REAL, " +
BABIES_THEME + " TEXT" + " );";
db.execSQL(CREATE_TBL_BABIES);
}
public Babies getBabyById(Long id){
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TBL_BABIES + " WHERE " + BABIES_BABY_ID
+ " = \"" + id + "\";";
Cursor cursor = db.query(TBL_BABIES,
null,
BABIES_BABY_ID + " = " + id,
null, null, null, null);
if (cursor != null && cursor.getCount() > 0) {
//for testing getInt
int id = cursor.getInt(cursor.getColumnIndex(BABIES_BABY_ID));
String name = cursor.getString(cursor.getColumnIndex(BABIES_NAME));
cursor.close();
}
是的,您可以在任何地方使用$ scope.time,但如果您尝试使用&#34;然后&#34;,它将不会被定义。您可以在视图{{$ scope.time}}中放置某个位置并探测它是否会在$ http.get
之外定义如果你得到undefined,很可能res.data [$ scope.numSerie]的索引超出界限。
首先使用浏览器的开发者工具检查是否有错误。 $ scope.numSerie似乎是罪魁祸首,检查其价值或提供更多细节