【问题标题】:Use run a particular code first使用先运行特定代码
【发布时间】:2016-06-16 17:31:35
【问题描述】:

【问题讨论】:

  • 显示角度承诺代码
  • 现在在问题中编辑
  • 我没有问你从哪里获得帮助。显示您编写的代码。
  • 这与我使用的代码相同。我希望首先调用 ajax 调用。但那没有发生。我想知道我是否可以将此 ajax 调用放在配置中的某个位置,并确保配置文件是否首先运行,然后是其他页面控制器。
  • 不,它不能那样工作。你打电话然后等待响应而不是继续前进。我仍然对您现有的代码感到困惑,为什么不将其复制并粘贴到这个问题中?

标签: c# angularjs visual-studio configuration


【解决方案1】:

配置块非常适合两段可能对您有所帮助的代码。

首先,您可以使用它来注入一个 $http 拦截器,该拦截器将处理失败的身份验证调用和重定向。

angular.module("app", [])
    .config(function ($httpProvider) {
        $httpProvider.interceptors.push("authInterceptor");
    });

您可以将此 $http 拦截器 编写为名为“authInterceptor”的工厂(未显示)。更多here,但重点是它可以从 $http 响应中查找某些状态码,例如 401,并根据需要重定向到您的错误页面

根据您正在使用的路由,您可以使用路由 resolve 属性来保持加载路由,直到数据被解析。如果被拒绝,您创建的拦截器将重新路由

angular.module("app", [])
    .config(function ($routeProvider, $httpProvider, $http) {
        $routeProvider
            .when('/', {
                controller:'MainCtrl',
                template:'<h1>Hello!<h1>',
                resolve:{
                    userData: return $http.get('/api/authentication');
                }
            });
        $httpProvider.interceptors.push("authInterceptor");
    });

最后一种选择是运行块代替进行初始身份验证调用。 run 块在配置之后但在您的应用加载之前运行。

angular.module("app", [])
    .config(function ($routeProvider, $httpProvider, $http) {
        $httpProvider.interceptors.push("authInterceptor");
    })
    .run(function ($http) {
        $http.get('/api/authentication');
    });

我不会尝试只运行此代码。您必须编写拦截器服务。您必须加载路由器模块等。希望这会有所帮助。

【讨论】:

    【解决方案2】:

    $.ajax 替换为 angular 的 $http 并等待 promise 调用:

    var checkUserlogin = function() {
        return $http.get(serviceURL_CheckUserExists)
               .then(function (response) {
                    if (response.Results.length == 1 && response.Results[0].BlockUser == false) {
                        return response.Results[0].User_ID.trim();
                    } else {
                        return null; // could not login
                    }
               });
    };
    

    PS:我没有测试过这段代码,如果你有任何错误请告诉我。

    【讨论】:

    • Shaharyar- 尝试了这段代码,它仍然显示加载页面
    • 它在发出事件getUserName 时做了什么?你为什么要毫无条件地打电话给loadData
    • 它只是将结果发送给其他控制器......所以他们可以抓住它并使用它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多