作用域变量在REST API POST请求中丢失值


Scope Variable Losing Value on REST API POST Request

Game Create Controller createGame函数通过HTML文件被ngClick调用。当函数到达console.log时,$scope.gameData的值是正确的。然而,当请求通过Laravel 5 REST API发送时,请求中没有任何内容。只是为了澄清,我说的是导致问题的这一行:

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

请求成功返回,因为不需要名称,并且在数据回调中创建并发送了ID。

我已经做了3个其他完整的主题(游戏是一个完整的主题),其中创建逻辑工作得很好。这个create函数中的逻辑与其他的没有什么不同,但是由于某种原因,name值没有通过REST API发送。

如果您需要更多代码或有任何问题,请告诉我。

Game Create Controller

'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);
<<p> API服务/strong>
'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);

Game Laravel 5 Controller

<?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);
        }
    }
}

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

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

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

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

解决方案:

$scope.gameData = {};