【发布时间】:2018-06-10 18:26:18
【问题描述】:
我正在开发我的第一个 AngularJS 应用程序,我在后端使用 Python/Flask/Rest API。我的 app.js 文件中有一个脚本,用于处理登录的表单。该脚本按预期工作,但是一旦该人登录我想做两件事,将 JWT 存储在 localStorage 中,我已经完成了。
现在我有一个有效的 JWT,在同一个函数中,我想运行另一个请求,为我提供登录人的信息。我能够运行请求并取回有效数据,但我无法存储此数据在一个变量中以通过 HTML 页面使用。我已经使用 $rootScope 来存储和访问它,但我觉得这可能不是正确的方法,并且我想确保我做的事情正确。
这是我的 app.js 代码;
var app = angular.module('app', []);
app.controller('FormLoginCtrl', function ($scope, $http, $window, $rootScope) {
$scope.form = {
email: "",
password: "",
};
$scope.submitForm = function() {
$http({
url: "http://127.0.0.1:5000/auth/login_user",
data: JSON.stringify($scope.form),
method: 'POST',
}).success(function(data){
console.log("OK", data)
localStorage.token = data.token
sessionStorage.token = data.token
$http({
url: "http://127.0.0.1:5000/auth/login_user",
method: 'GET',
headers: {'X-API-KEY' : data.token}
}).then(function success(response){
console.log(response);
$rootScope.user = response.data;
})
}).error(function(err){"ERR", console.log(err)})
};
});
我的 HTML 表单代码;
<form name="login" ng-controller="FormLoginCtrl" ng-submit="submitForm()" id="login" class="contact-form-wrapper">
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<input id="inputEmail" ng-model="form.email" type="test" class="form-control" placeholder="Your Email">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<input id="password" ng-model="form.password" type="text" class="form-control" placeholder="Your Password">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-sm-12">
<button type="submit" ng-click="Submit" class="btn btn-primary btn-sm mt-5">Login</button>
</div>
在我试图调用变量的 main-menu.html 文件中;
<ul class="nav navbar-nav" id="responsive-menu">
<li><a href="index.html">Write A Review</a></li>
<li ng-hide="user"><a href="signin.html">Sign In</a></li>
<li ng-hide="user"><a href="register.html">Register</a></li>
<li>
<a ng-show="user" href="category-01.html">Welcome {{ user['first_name'] }}</a>
<ul ng-show="user">
<li ng-show="user"><a href="agent-grid.html">My Profile</a></li>
<li ng-show="user"><a href="agent-list.html">My Reviews</a></li>
</ul>
</li>
</ul>
我应该添加它当前正在工作,但我知道这可能不是正确的方法。感谢您的帮助。
【问题讨论】:
-
设计问题。您可以拥有一个包装和存储值的服务,但最终它将以某种方式成为全局变量。你是对的,把它放在
$rootScope上是个坏主意。这意味着每个视图都可以隐式访问它。您应该创建一个服务来存储它并提供对它的受控访问。 -
与@AluanHaddad 达成一致,这就是服务的用途:跨控制器共享数据。
-
我不熟悉服务,因此需要阅读相关服务。感谢您的意见。
标签: javascript angularjs