简体   繁体   English

Angular ui-router 没有将解析注入控制器

[英]Angular ui-router not injecting the resolve into controller

I'm just getting started with Angular and Express and facing tough times with it.我刚刚开始使用 Angular 和 Express,并面临着困难时期。 I come from a java background and want to learn Angular and Express and therefore trying out to build one small application.我来自 Java 背景,想学习 Angular 和 Express,因此尝试构建一个小型应用程序。

What I'm trying to do : I have given a password reset link to user so as to change his password.我想做什么: 我已经给用户一个密码重置链接,以便更改他的密码。 The link is something like:链接是这样的:

localhost:9000/reset/:token本地主机:9000/重置/:令牌

Now, I have created a simple view which shows an input box to change his password if token is valid otherwise prints an error if token is invalid based on ng-show property of angular.现在,我创建了一个简单的视图,它显示了一个输入框,如果令牌有效则更改他的密码,否则如果基于 ng-show angular 属性的令牌无效则打印错误。

Problem : Before I can render my above created view, I want ui-router to check if the :token is valid or not.问题:在渲染上面创建的视图之前,我希望 ui-router 检查 :token 是否有效。 I will be using the information of validity of token in my controller to control ng-show property mentioned above.我将在我的控制器中使用令牌的有效性信息来控制上面提到的 ng-show 属性。

After reading this I tried to leverage the $stateProvider.state functionality with a resolve so as to get the response of validation of token as pre-requisite.阅读本文后,我尝试利用 $stateProvider.state 功能进行解析,以便将令牌验证的响应作为先决条件。 This will help me when rendering the actual view where I'm using ng-show technique to show error message or input box to change the password based on the ui-router resolve promiseObject.这将有助于我在渲染实际视图时使用 ng-show 技术显示错误消息或输入框以根据 ui-router 解析 promiseObject 更改密码。

What is the issue now ?现在的问题是什么?

Well, after breaking my head for too long, I decided to post my question over here.好吧,在打破我的头太久之后,我决定在这里发布我的问题。 Can anyone please help me here ?任何人都可以在这里帮助我吗?

My questions:我的问题:

1. I'm able to get the data/err from the api call but somehow ui-router is not injecting it in my controller. 1.我能够从 api 调用中获取数据/错误,但不知何故 ui-router 没有将它注入我的控制器中。 Can anyone tell me am I doing anything wrong here ?谁能告诉我我在这里做错了什么?

2. Right now if the token is not valid, I'm returning a 404 in response from my backend api. 2.现在,如果令牌无效,我将从后端 api 返回 404 作为响应。 But the factory method in frontend takes it as err (Is this expected in Node.js ?) and the err is thrown which results in deferred.reject().但是前端的工厂方法将其视为错误(这是在 Node.js 中预期的吗?)并且抛出错误导致 deferred.reject()。 Now, if I go with ui-router definition, if the promise is not resolved then the view won't be rendered, right ?现在,如果我使用 ui-router 定义,如果 promise 没有得到解决,那么视图将不会被呈现,对吧? Is there any way by which I can pass this err also to my controller ?有什么方法可以将这个错误也传递给我的控制器吗? Reason why I'm asking to pass err is, my view's ng-show logic is based on the response code (4xx/2xx) depending on which I'll show error message or input box.我要求传递 err 的原因是,我视图的 ng-show 逻辑基于响应代码 (4xx/2xx),具体取决于我将显示错误消息或输入框。

Code snippets:代码片段:

Factory Method which calls the rest api:调用其余 api 的工厂方法:

  isPasswordResetTokenValid: function(token, callback) {
    var cb = callback || angular.noop;
    var deferred = $q.defer();

    return User.getUserByPasswordResetToken(token,
      function(data) {
        deferred.resolve(data);
        return cb(data);
      },
      function(err) {
        deferred.reject(err);
        return cb(err);
      }.bind(this)).$promise;
  } 


'use strict';

angular.module('scrubApp')
  .config(function ($stateProvider) {
    $stateProvider
      .state('passwordreset', {
        url: '/reset/:token',
        templateUrl: 'app/account/passwordreset/passwordreset.html',
        resolve: { 

          promiseObj2: function($stateParams, Auth){
              var token = $stateParams.token;
              console.log(token);
               var response = Auth.isPasswordResetTokenValid({token: token})
              .then( function(response) {
                  console.log(response); // shows response
                  if(response.status == 404) {
                    //$scope.token-expiry = true;
                    return response;
                  }
                  if(response.status == 200) {
                    // $scope.user = response.data;
                  }
              })
              .catch( function(err) {
                console.log(err); // shows error
                return err;
              });
          }
        },
        controller: 'ResetPasswordCtrl'  
      });
  });

ResetPasswordCtrl controller: ResetPasswordCtrl 控制器:

'use strict';

angular.module('myApp')
  .controller('ResetPasswordCtrl', function ($scope, User, Auth, Mailer, $stateParams, promiseObj2) {
    $scope.errors = {};
    $scope.user = {};

    console.log(promiseObj2);   // This is coming undefined
    $scope.isTokenExpired = promiseObj2;  // Not able to inject promiseObj2

    $scope.isFormSubmitted = false;


  });

Thanks in advance提前致谢

Your resolve promiseObj2 should return a promise from promise service, so that your controller will wait till promise gets resolved.你的 resolve promiseObj2应该从 promise 服务返回一个 promise,这样你的控制器就会等到 promise 被解析。

return Auth.isPasswordResetTokenValid({token: token})

Update更新

If you want to handle some logic on failure of your token request then you could handle it in your promise itself, that can do couple of thing like如果您想在令牌请求失败时处理一些逻辑,那么您可以在您的承诺中处理它,这可以做一些事情,例如

  1. You could redirected to other page using $state.go('login') or $state.go('error') page.您可以使用$state.go('login')$state.go('error')页面重定向到其他页面。

Code代码

promiseObj2: function($stateParams, Auth, $state){
  var token = $stateParams.token;
  console.log(token);
  return Auth.isPasswordResetTokenValid({token: token}) //added return here
  .then( function(response) {
    console.log(response); // shows response
    if(response.status == 404) {
        $state.go('error')
    }
    if(response.status == 200) {
        return response;
    }
  })
  .catch( function(err) {
    console.log(err); // shows error
    return err;
  });
}
  1. If you want to show html page anyhow if error occurs then You could also return data from the .then of promiseObj2 object that will have information about error message.如果你想反正显示HTML网页,如果发生错误,那么你也可以从返回的数据.thenpromiseObj2对象,将有关错误消息的信息。 So that error information is return to the controller以便将错误信息return给控制器

Code代码

promiseObj2: function($stateParams, Auth, $state){
  var token = $stateParams.token;
  console.log(token);
  return Auth.isPasswordResetTokenValid({token: token}) //added return here
  .then( function(response) {
    console.log(response); // shows response
    if(response.status == 404) {
      return {status: 404, data: "doen't found resource"}
    }
    if(response.status == 200) {
        return response;
    }
  })
  .catch( function(err) {
    console.log(err); // shows error
    return err;
  });
}

Then inside controller we will get resolve the promise of promiseObj2 object and then you will get the value of error in the .then function of it.然后在控制器内部,我们将解析promiseObj2对象的 promise,然后您将在它的.then函数中获得 error 的值。

angular.module('myApp')
.controller('ResetPasswordCtrl', function ($scope, User, Auth, Mailer, $stateParams, promiseObj2) {
  $scope.errors = {};
  $scope.user = {};
  promiseObj2.then(function(resp){
    console.log(resp)
    $scope.isTokenExpired = resp.isTokenExpired;
  }, function(err){
    console.log(err)
  })
});

Update更新

If we want to handle a condition where server return 4XX status that means our ajax will call catch function that won't return promise though.如果我们想处理服务器返回4XX状态的情况,这意味着我们的 ajax 将调用不会返回承诺的 catch 函数。 We could solve this case by creating custom promise using $q and we will resolve it from the promiseObj2我们可以通过使用$q创建自定义承诺来解决这种情况,我们将从promiseObj2解决它

Code代码

promiseObj2: function($stateParams, Auth, $state, $q){
  var token = $stateParams.token,
      deffered = $q.defer();
  console.log(token);
  Auth.isPasswordResetTokenValid({token: token}) //added return here
  .then( function(response) {
    console.log(response); // shows response
    if(response.status == 404) {
      //return {status: 404, data: "doen't found resource"}
      deffered.resolve({status: 404, data: "doen't found resource"});
    }
    if(response.status == 200) {
      //return response;
      deffered.resolve(response);
    }
  })
  .catch( function(err) {
    console.log(err); // shows error
    deffered.resolve(err);
  });
  return deffered.promise;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM