角路由解析调用服务 [英] Angular route resolve calling a service

查看:53
本文介绍了角路由解析调用服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力使Angular路线解析工作.对于像这样的javascript框架中更复杂的部分,我发现文档没什么用.

I'm struggling to get Angular route resolve working. I find the documentation less than useless for more complex parts of the javascript framework like this.

我提供以下服务:

app.service("AuthService", ["$http", "$q", function($http, $q){

  this.test = function(){
    return $q(function(resolve, reject){
      var auth = false;
      resolve(auth);
    });
  }

}]);

现在我的路线如下:

app.config(["$routeProvider", "$locationProvider", function($routeProvider, $locationProvider){

  $locationProvider.html5Mode(true).hashPrefix("!");

  $routeProvider

  .when("/account", {
    templateUrl: "/views/auth/account.html",
    controller: "AccountController",
    resolve: {
      auth: ["AuthService", function(AuthService) {
        return AuthService.test().then(function(auth){
          if (auth) return true;
          else return false;
        });
      }]
    }
  });

}]);

我想在这里发生以下事情:

What I want to happen here is the following:

  • 用户转到/account
  • AuthService被触发并返回变量(true或false)
  • 在解析中,如果返回的值为false,则无法加载路由
  • 如果返回的值为true,则表明用户已通过身份验证并可以查看路线

我认为我还没有完全理解如何使用resolve,到目前为止,我的方法还行不通.有人可以解释一下这样做的正确方法吗?

I don't think I've fully understood how to use resolve and my method so far does not work. Could someone please explain the correct way to do this?

推荐答案

配置路线时的resolve块旨在使导航基于有条件的承诺或拒绝的条件.

The resolve block when configuring routes is designed to make navigation conditional based upon the resolution or rejection of a promise.

您正在尝试通过解析值为 true false

You are attempting to handle this by resolving with a resolution value of true or false

请尝试以下操作:

resolve: {
  auth: ["AuthService", function(AuthService) {
    return AuthService.test().then(function(auth){
      if (!auth){
        throw 'not authorized';
      }
    });
  }]
}

这将导致承诺被拒绝,因此不允许路由继续/完成.

This will cause the promise to be rejected and therefore not allow the routing to continue/complete.

还要注意的是,从promise决议中得出的值将被注入到处理控制器中

Also of note is that the value coming out of the promise resolution will be injected into the handling controller

这篇关于角路由解析调用服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆