簡體   English   中英

在使用Angular.js然后連接到Rails API時如何注冊用戶?

[英]How do I register a user, while using Angular.js and then connecting to a Rails API?

我要做的就是在前端安裝一個Angular連接到Rails api來注冊/登錄用戶。 我需要有關如何進行身份驗證的幫助。 將CORS gem安裝在rails api上。 如果有任何好的樣板或好的文件,請發送鏈接! 提前致謝!

登錄部分:

<form name="regField" ng-submit="create(user, regField.$valid)" novalidate>
<fieldset>
    <legend>Register</legend>
    <label>Username<input type="text" ng-model="user.username" required></label>
    <label>PW<input type="password" ng-model="user.password" required></label>
    <label>PW confirm<input type="password" ng-model="user.pw_confirm" required></label>
    <button>Submit</button>
</fieldset>

登錄控制器:

app.controller('loginController', ['$scope','$location','userFactory', function($scope, $location, UserFactory){
$scope.loginErr = "";
$scope.regErr = "";
// UserFactory.allAppointments();
$scope.create = function(user, isValid){
    if(isValid){
        UserFactory.create(user,function(res){
            if(res.data.duplicate){
                $scope.regErr = "Username must be unique";
            } else {
                $location.url('/dashboard');
            }
        })
    } else{
        $scope.regErr = "Invalid Combination";
    }
}
$scope.login = function(user, isValid){
    if (isValid){
        UserFactory.login(user,function(){
            $location.url('/dashboard');
        })
    } else {
        $scope.loginErr = "Invalid Combination";
    }
}
}])

UserFactory:

app.factory('userFactory', ['$http', function($http){
var currentUser = {};
return {
    getCurrentUser: function(callback){
        $http({
            method:  "GET",
            url: "/currentUser"
        }).then(function(user){
            currentUser = user;
            callback(user.data);
        })
    },
    create:function(user, callback){
        $http({
            method:"POST",
            url:"https://nameofapp.herokuapp.com/api/v1/auth",
            dataType:'json',
            headers: {
                'Content-Type': 'application/json'
            }
        }).then(function(user){
            currentUser = user;
            callback(user);
        })
    },
    login:function(user,callback){
        $http({
            method:"POST",
            url:"/login",
            data:user
        }).then(function(user){
            currentUser = user;
            callback(user);
        })
    },
    logout: function(callback){
      $http({
        method:"GET",
        url:'/logout'
      }).then(callback)
    }
}
}])

您可以參考Angular + Rails-api + Devise設置身份驗證https://www.airpair.com/ruby-on-rails/posts/authentication-with-angularjs-and-ruby-on-rails

暫無
暫無

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

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