REST API POST请求中的范围变量丢失值

时间:2015-10-17 19:46:25

标签: javascript php angularjs rest

游戏创建控制器createGame函数由ngClick通过HTML文件调用。当函数到达console.log时,$scope.gameData中的值是正确的。 但是,当通过Laravel 5 REST API发送请求时,请求中没有任何内容。仅仅是为了澄清,我正在谈论导致问题的这一行:

APIService.postData('game', '', $scope.gameData).then(function (data) {

请求返回成功,因为该名称不是必需的,并且ID是在数据回调中创建并发回的。

我已经完成了3个其他完整主题(游戏是一个完整主题),其中创建逻辑工作正常。此create函数中的逻辑与其他函数没有区别,但由于某种原因,name值未通过REST API发送。

如果您需要更多代码或有任何疑问,请与我们联系。

游戏创建控制器

'use strict';

function GameCreateController($scope, APIService, $state) {

    $scope.race_counter = 0;
    $scope.class_counter = 0;

    $scope.gameData = [];
    $scope.gameData.name = '';
    $scope.gameData.classes = [{id: $scope.class_counter}];
    $scope.gameData.races = [{id: $scope.race_counter}];

    this.createGame = function() {

        $scope.loading = true;
        var newGameID = '';

        // --- Has value for $scope.gameData.name, but when the request is sent, there is nothing in the request at all.
        console.log($scope.gameData);

        APIService.postData('game', '', $scope.gameData).then(function (data) {
            newGameID = data.id;

            angular.forEach($scope.gameData.classes, function (key, value) {
                if (typeof $scope.gameData.classes[value].name != 'undefined' &&
                    typeof $scope.gameData.classes[value].icon != 'undefined') {
                    $scope.gameData.classes[value].game_id = newGameID;
                    APIService.postData('game-class', '', $scope.gameData.classes[value]);
                }
            });

            angular.forEach($scope.gameData.races, function (key, value) {
                if (typeof $scope.gameData.races[value].name != 'undefined' &&
                    typeof $scope.gameData.races[value].icon != 'undefined') {
                    $scope.gameData.races[value].game_id = newGameID;
                    APIService.postData('game-race', '', $scope.gameData.races[value]);
                }
            });

            $scope.loading = false;
            $state.go('app.games', {successMessage: 'Game has been created.'});
        })
    };

    this.addClassRow = function() {
        $scope.class_counter++;
        $scope.gameData.classes.push({id: $scope.class_counter});
    };

    this.deleteClassRow = function(rowNo) {
        $scope.class_counter--;
        $scope.gameData.classes.splice(rowNo, 1);
    };

    this.addRaceRow = function() {
        $scope.race_counter++;
        $scope.gameData.races.push({id: $scope.race_counter});
    };

    this.deleteRaceRow = function(rowNo) {
        $scope.race_counter--;
        $scope.gameData.races.splice(rowNo, 1);
    };

    this.cancelGame = function() {
        $state.go('app.games');
    };
}

App.controller('GameCreateController', GameCreateController);

API服务

'use strict';

function APIService($q, $http, sanitizeFormInputService, BASE_URL_BACKEND, API) {

    return {
        getData: function (route, param) {
            var defer = $q.defer();
            $http.get(BASE_URL_BACKEND + API + route + '/' + param).success(function (data) {
                    defer.resolve(data);
                }
            ).error(function (data) {
                    defer.reject(data);
                }
            );
            return defer.promise;
        },

        postData: function (route, param, postData) {

            var defer = $q.defer();
            var request = '';

            if (route == 'upload') {
                request = $http({
                    method: 'post',
                    url: BASE_URL_BACKEND + API + route + '/' + param,
                    data: postData,
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                });
            } else {
                request = $http({
                    method: 'post',
                    url: BASE_URL_BACKEND + API + route + '/' + param,
                    transformRequest: sanitizeFormInputService,
                    data: angular.toJson(postData)
                });
            }

            request.success(function (data) {
                defer.resolve(data);
            });

            request.error(function (data) {
                defer.reject(data);
            });

            return defer.promise;
        },

        putData: function (route, param, putData) {

            var defer = $q.defer();
            var request = '';

            if (route == 'upload') {
                request = $http({
                    method: 'put',
                    url: BASE_URL_BACKEND + API + route + '/' + param,
                    data: putData,
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                });
            } else {
                request = $http({
                    method: 'put',
                    url: BASE_URL_BACKEND + API + route + '/' + param,
                    transformRequest: sanitizeFormInputService,
                    data: angular.toJson(putData)
                });
            }

            request.success(function (data) {
                defer.resolve(data);
            });

            request.error(function (data) {
                defer.reject(data);
            });

            return defer.promise;
        },

        deleteData: function (route, param) {
            var defer = $q.defer();
            $http.delete(BASE_URL_BACKEND + API + route + '/' + param).success(function (data) {
                    defer.resolve(data);
                }
            ).error(function (data) {
                    defer.reject(data);
                }
            );
            return defer.promise;
        }
    };
}

App.factory('APIService', APIService);

游戏Laravel 5控制器

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Models\Game;
use Exception;
use Input;

class GameController extends Controller
{
    public function index()
    {
        return Game::with('classes', 'races')->get();
    }

    public function store(Request $request)
    {
        return Game::create($request->all());
    }

    public function show($id)
    {
        $game = Game::with('classes', 'races')->where('id', '=', $id)->get();
        return response()->json($game[0], 200);
    }

    public function update(Request $request, $id)
    {
        try {
            $game = Game::find($id);
            $game->name = $request->name;
            $game->save();
            return response()->json($game, 200);
        } catch (Exception $e) {
            return response()->json(array(
                'status' => 'error',
                'message' => 'Error updating record: ' . $e->getMessage()
            ), 500);
        }
    }
}

1 个答案:

答案 0 :(得分:3)

您的问题在于撰写数据的方式,以及将其传递给POST方法的方式。

$scope.gameData = [];
$scope.gameData.name = '';

您的数据被初始化为一个数组,然后您将属性作为对象附加到它(是的,数组是JS中的一个对象,它可以工作!)。但是,当您传递这样的数组时,angular.toJson()方法并不能很好地工作。它返回一个空数组:[]

data: angular.toJson(postData); // results in []

解决方案:

$scope.gameData = {};