簡體   English   中英

使用Angular將請求發布到NodeJS,Express

[英]Post request with Angular to NodeJS, Express

我正在用angluar創建第一個應用程序,還使用帶有快速框架的nodejs創建了第一個應用程序,所以我有幾個問題。

  1. 如何將數據(json)發布到服務器-如何在發布請求中將json傳遞到服務器,現在可以使用,但是獲取請求嘗試調用appName:/#/ games / game_id / results嗎?priority = 0&priority = 0&...
  2. 當我返回json時,如何以他的控制器可以看到從服務器返回的json的方式重定向到其他角度視圖

controllers.js

$scope.generate = function() {
    Generator.gPriority({gameId: $routeParams.gameId, priority: $scope.priority}, function() {
        $location.path("/games"); //redirect when get json from server to other view/controller/partias and process json ...show json in table
    });
};

service.js

var appServices = angular.module('appServices', ['ngResource']);

appServices.factory('Generator', ['$resource',
    function($resource){
        return $resource('games/:gameId/results', {}, {
            gRandom: {method:'GET', params:{gameId:''}, isArray:true},
            gPriority: {method: 'POST', params:{gameId:'',priority: '@priority'}}
        });
    }
]);

server.js

app.post('/games/:id/results', generator.gWithPriority);

generator.js

exports.gWithPriority = function(req, res) {
    var priority = req.body;
    console.log('Game priority: ' + JSON.stringify(priority));
    res.json({
     "numbers": [
            [[8,7,6,5,4,3,2,1],[1,2]],
            [[3,2,3,4,5,6,7,8],[1,3]],
            [[4,2,3,4,5,6,7,8],[1,2]]
         ]
    });
}; 

對不起,我的英語不好。

我可以為號碼2提供幫助。如果要在控制器之間共享數據,請使用服務。 例如:

angular.module('myApp').factory('DataService', function(){
    var data = {};
    return {
        getData: function() { return data; },
        setData: function(newData) { data = newData; }
    };
});

Generator.gPriority(...)的回調中使用setter,並在新視圖的控制器中使用getter。 這樣,您可以將數據從一個控制器傳遞到服務,然后從其他控制器檢索該數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM