在AngularJS中重定向到不同相对URL路径的正确方法是什么? (即更改URL - 可能是$ location.path - 然后刷新)

时间:2017-04-03 03:18:41

标签: angularjs

假设这是我的HTML(在访问路径/时提供服务:

<form ng-submit="ctrl.loginUser()" name="myLoginForm">
    <div class="form-group">
        <label>Username</label>
        <input type="text" name="uname" class="form-control" ng-model="ctrl.loginuser.username" required> 
    </div>

    <div class="form-group">
        <label>Password</label>
        <input type="password" name="pwd" class="form-control" ng-model="ctrl.loginuser.password" required>
    </div>

    <input type="submit" value="Login"> 
</form>

这是我访问/homemainPage.html)时显示的HTML页面:

<h5>TESTTT</h5>

这是在提交表单时调用的内容:

angular.module("BaseApp", [])
    .config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.xsrfCookieName = 'csrftoken';
        $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
    }])

    .config(['$locationProvider', function($locationProvider){
        $locationProvider.html5Mode(true);
    }])

self.loginUser = function(loginuser) {
    return $http.post("/custom-api-auth/login", loginuser)
    .then(function(response) {
        $location.url("/home");
    });
};

我尝试过测试并提交表单。该网址确实更改为/home,但未显示转到网址www.url.com/home时提供的网页。页面也不刷新。

如前所述,我转到www.url.com/homemainPage.html确实出现了。

我需要采取哪些措施才能正确重定向到/home网址?

1 个答案:

答案 0 :(得分:0)

我使用ui-router的方式你可以在这里阅读更多内容。

https://github.com/angular-ui/ui-router/wiki

您可以使用resolve为控制器提供自定义状态的内容或数据。在这种情况下,如果你想去测试,但之前你需要填写一个承诺,这将是一个例子。

$stateProvider.state('test', {
  resolve:{

     // Example using function with simple return value.
     // Since it's not a promise, it resolves immediately.
     simpleObj:  function(){
        return {value: 'simple!'};
     },

     // Example using function with returned promise.
     // This is the typical use case of resolve.
     // You need to inject any services that you are
     // using, e.g. $http in this example
     promiseObj:  function($http){
        // $http returns a promise for the url data
        return $http({method: 'GET', url: '/someUrl'});
     },



  },