【问题标题】:How to return a HTML page with AngularJS如何使用 AngularJS 返回 HTML 页面
【发布时间】:2016-08-06 14:59:40
【问题描述】:

我有一个 JAVA Spring 服务器,我正在尝试使用控制器返回一个 HTML 页面,但问题是我不知道使用 Angular 加载页面的正确方法是什么。还是我做错了?

JAVA

@Controller
public class Login {
@RequestMapping(value="/login", method=RequestMethod.POST)
public @ResponseBody String testLogin(@RequestBody LoginInfo login) throws MyException{
    if (login.getUser().equals("test") && login.getPass().equals("1234")){
    return "main.html";
    } else {
        throw new MyException("Wrong login info");
    }
}

AngularJS

$scope.login = function(){
url = "/login";
$http.post(url,{
    "user":$scope.user,
    "pass":$scope.pass  
}).then(
        function (response){
        // what should be here???
        });};

【问题讨论】:

  • 您的 java 代码显示您想要加载 html 页面,但您的 Angular 代码显示您想要进行登录 api 调用
  • 通过路由器获取您的模板并使用 $http 对象提供您的凭据。

标签: javascript java angularjs


【解决方案1】:

您必须从您的 JAVA 控制器返回 true 或 false

@Controller
public class Login {
@RequestMapping(value="/login", method=RequestMethod.POST)
public @ResponseBody String testLogin(@RequestBody LoginInfo login) throws MyException{
    if (login.getUser().equals("test") && login.getPass().equals("1234")){
        return true;
    } else {
        return false;
        throw new MyException("Wrong login info");
    }
}

然后在 AngularJS 中:

1] 如果您使用 Angular Route,则使用 $location.path()

2] 如果你使用 angular-ui-router,那么使用 $state.go()

1] 示例:

$scope.login = function() {
    url = '/login';
    $http.post(url,{
        "user":$scope.user,
        "pass":$scope.pass  
    }).then(function (response) {
        if(response) {
            $location.path('/main');
        } else {
            $location.path(url);
        }
    });
};

【讨论】:

  • 它工作了,但现在 URL 是 localhost:8080/#/main,应该是 localhost:8080/main.html,我尝试设置 $routeProvider$locationProvider.html5Mode(true),但它仍然不起作用。
  • 在 index.html 中添加代码:<head> <meta charset="utf-8"> <base href="/"> </head> 更多信息:link
猜你喜欢
  • 2014-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-01
相关资源
最近更新 更多