AngularJS:工厂返回对象的正确方法?

时间:2015-04-23 18:59:35

标签: javascript angularjs angularjs-factory

我有一个POST数据要在Angular.js项目中进行检索。这是我的工厂:

angular.module('mtApp').factory('getKey', function($http) {
    return {
        getData: function(data) {
            var key='';
            return $http({
                url: '../php/key_gen.php',
                method: "POST",
                headers: {'Content-Type': 'application/json'}
                }).success(function (data) {
                    console.log(data); //value is right as expected
                    return data;
                })
                .error(function (data, status, headers, config) {
                    console.log('Erro : ' + status + ' ' + headers);
                });
        }
    }
});

我获取数据的方式是:

$scope.key = 'ok';

getKey.getData()
.success(function($scope,data){
    $scope.key = data.GeneratedKey;
    console.log(data.GeneratedKey); //undefined
    console.log(data);  //200 o.O
});

console.log($scope.key); //still 'ok' O.o

正如您在我的代码中看到的,我有几个console.log调用。当我运行应用程序时,我唯一看到的是:

mtapp.controller.js:13 ok
mtapp.app.js:52 Object {GeneratedKey: "d1bc7a5e840a6c24d87b90dde9e075de1f0e3b34978ca9f319…69d839b4e2a004e1f8d728939867afe189cfb8848c6a8ee38"}
mtapp.controller.js:9 undefined
mtapp.controller.js:10 200

mtapp.app.js:52行中的值应与mtapp.controller.js:10相同。但是当我尝试在日志中查看时,工厂中的对象只有200的值...

我的目标是从工厂的JSON( GeneratedKey )获取值到控制器($ scope.key 中的)。

我做错了什么? :(

3 个答案:

答案 0 :(得分:2)

因为您正在处理作为状态代码的第二个参数,所以您应该从那里删除$scope并使用data本身

<强>代码

getKey.getData()
.success(function(data, status, headers, config){ <---here $scope should remove
    $scope.key = data.GeneratedKey;
    console.log(data.GeneratedKey);
    console.log(data);
});

答案 1 :(得分:0)

正如 Kevin 所说,主要问题是angular.js的异步方式。

Só最大的问题是最后一行

console.log($scope.key); //still 'ok' O.o

需要在调用工厂的函数结束之前设置。并且$ scope已从函数中移除以正常工作,因为 pankajparkar 表示。

$scope.key = 'ok';

getKey.getData()
.success(function(data){ // removed the $scope
    $scope.key = data.GeneratedKey;
    console.log($scope.key); //Moved up and it shows correctly in the console
    ... the rest of my code ...
});

我不知道它是否是最佳解决方案,但现在可以使用! :d

答案 2 :(得分:-1)

请尝试在工厂中使用$ q。

4758-4758/com.example.ananaybatra.rape_freeindia D/AndroidRuntime﹕ Shutting down VM
04-24 01:39:13.014    4758-4758/com.example.ananaybatra.rape_freeindia W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x415ffba8)
04-24 01:39:13.030    4758-4758/com.example.ananaybatra.rape_freeindia E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.ananaybatra.rape_freeindia, PID: 4758
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ananaybatra.rape_freeindia/com.example.ananaybatra.rape_freeindia.MainActivity}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2221)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2280)
        at android.app.ActivityThread.access$800(ActivityThread.java:141)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1202)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5059)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
        at android.support.v7.app.ActionBarActivityDelegate.onCreate(ActionBarActivityDelegate.java:152)
        at android.support.v7.app.ActionBarActivityDelegateBase.onCreate(ActionBarActivityDelegateBase.java:149)
        at android.support.v7.app.ActionBarActivity.onCreate(ActionBarActivity.java:123)
        at com.example.ananaybatra.rape_freeindia.MainActivity.onCreate(MainActivity.java:15)
        at android.app.Activity.performCreate(Activity.java:5312)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2178)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2280)
        at android.app.ActivityThread.access$800(ActivityThread.java:141)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1202)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5059)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)