在angularJs中返回请求响应

时间:2017-05-11 14:39:34

标签: javascript angularjs json node.js promise

我已经设置了一个控制器和服务来从我自己的NodeJS API / MongoDB端点获取一些JSON。

在我的浏览器控制台中,我看到一个返回的对象和5个项目,当我查询我的api时,我在浏览器中看到相同的json,所以我知道它在服务器端工作。

我很困惑,为什么在尝试NG-Repeat时,我在页面上什么都没有,当我在控制台注销退回的数据时,它返回未定义。

我是HTTP模块的新手,我正在尝试将DB调用重构为服务,而不是在控制器中使用它。

---控制器代码---

vm.getDepartments = function() {
        vm.departments = DbService.getAllDepartments();
        console.log(vm.departments);

    }();

---服务代码(使用$ http)---

function getAllDepartments() {
        $http.get('/api/departments').then(function(err, response) {
            if (err) {
                console.log(err);
            }
            return response;

        });
    };

--- html page ---

<tbody>
                    <tr ng-repeat='dept in vm.departments'>
                        <td>{{ dept.departmentLong }}</td>
                        <td>{{ dept.departmentShort }}</td>
                        <td>
                            <button class='btn btn-warning'><span class='glyphicon glyphicon-edit'></span></button>
                            <button class='btn btn-danger' ng-click='vm.deleteDepartment(dept);'><span class='glyphicon glyphicon-ban-circle'></span></button>
                        </td>
                    </tr>
                </tbody>

1 个答案:

答案 0 :(得分:3)

您使用了错误的private void syncDataItem(){ Log.d(TAG, "PanicAlert AlarmStatus=" + isAlertActive(context)); PutDataMapRequest putDataMapRequest = PutDataMapRequest.create(PATH_ALARM); putDataMapRequest.getDataMap().putBoolean(FIELD_ALARM_ON, isAlertActive(context)); putDataMapRequest.setUrgent(); Wearable.DataApi.putDataItem(mGoogleApiClient, putDataMapRequest.asPutDataRequest()).await(); } 方法。

public class DataLayerListenerService extends WearableListenerService { private static final String TAG = "DataLayerSample"; private static final String PATH_ALARM = "/alarm_path"; private static final String FIELD_ALARM_ON = "alarm_on"; @Override public void onDataChanged(DataEventBuffer dataEvents) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "onDataChanged: " + dataEvents); } GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this) .addApi(Wearable.API) .build(); ConnectionResult connectionResult = googleApiClient.blockingConnect(30, TimeUnit.SECONDS); if (!connectionResult.isSuccess()) { Log.e(TAG, "Failed to connect to GoogleApiClient."); return; } for (DataEvent event : dataEvents) { //Force update of complication? How? } } 方法有两个参数:@Override public void onComplicationUpdate( int complicationId, int dataType, ComplicationManager complicationManager) { Log.d(TAG, "onComplicationUpdate() id: " + complicationId); if (mGoogleApiClient == null){ mGoogleApiClient = new GoogleApiClient.Builder(this) .addApi(Wearable.API) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build(); mGoogleApiClient.connect(); } int randomNumber = (int) Math.floor(Math.random() * 10); String randomNumberText = String.format(Locale.getDefault(), "%d!", randomNumber); // Create Tap Action so that the user can trigger an update by tapping the complication. Intent updateIntent = new Intent(getApplicationContext(), UpdateComplicationDataService.class); updateIntent.setAction(UpdateComplicationDataService.ACTION_UPDATE_COMPLICATION); updateIntent.putExtra(UpdateComplicationDataService.EXTRA_COMPLICATION_ID, complicationId); PendingIntent pendingIntent = PendingIntent.getService( getApplicationContext(), complicationId, updateIntent, 0); ComplicationData complicationData = null; switch (dataType) { case ComplicationData.TYPE_SHORT_TEXT: complicationData = new ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT) .setShortText(ComplicationText.plainText(String.valueOf(actualState))) .setTapAction(pendingIntent) .build(); break; if (complicationData != null) { complicationManager.updateComplicationData(complicationId, complicationData); } //onStartWearableActivityClick(); } then回调,将使用then()对象调用。

使用success方法,将error函数附加到返回的response

查看mine.

发布的旧答案

then()会返回承诺,因此您可以创建一个仅返回承诺的函数,如 @sachila ranawaka 所述。

callback

在控制器中使用我上面提到的然后方法。

promise

另一种方法是创建$http.get('/api/departments')函数,并将其传递给function getAllDepartments() { return $http.get('/api/departments') }; 方法。

 DbService.getAllDepartments().then(function(response) {
      vm.departments = response.data; 
      console.log(vm.departments);
 },function(error){
      console.log(err);
 });

控制器代码:

callback