【问题标题】:Async call back fires after method return (angularjs .then())方法返回后异步回调触发(angularjs .then())
【发布时间】:2015-11-21 16:55:19
【问题描述】:

我有以下代码:(我尝试了很多方法)

performLogin = (data: LoginRequest) => {
  var deferred = this.qService.defer();
  var response = this.httpService.get(
  myServiceURL + '&' + ObjecttoParams(data))
  .then(function (response) {
    debugger;
    this.loginResponse = JSON.parse(JSON.stringify(response.data));
  });
  debugger;
  deferred.resolve(response);
  debugger;
  return(this.loginResponse);
}

这是我的这个服务的构造函数:

  constructor($http: ng.IHttpService, $location: ng.ILocationService, $q: ng.IQService) {
            this.qService = $q;
            this.httpService = $http;
            this.locationService = $location;
            this.loginResponse = new LoginResponse();
            this.serviceURL = staticURL + currentServiceName;

        }

我正在调用我的控制器中的 performLogin,他们希望收到一个“LoginResponse”类,但是因为 .then() 稍后发生,所以我的“return this.loginResponse) 发生在 .then() 之前调用。

如何让他在返回之前等待 .then() 完成?

【问题讨论】:

    标签: angularjs asynchronous typescript


    【解决方案1】:

    Q 让您能够创建 Promise,这对于处理异步操作非常有帮助。但是http服务返回一个promise,所以需要自己创建。

    promise 是您希望从此方法返回的内容,它将允许此方法的使用者异步处理结果。

    performLogin = (data: LoginRequest): ng.IPromise<LoginResponse> => {
      var response = this.httpService.get(
          myServiceURL + '&' + ObjecttoParams(data))
        .then(function (response) {
          return response.data;
        });
      return response;
    };
    

    那么任何调用performLogin的东西都可以这样做:

    foo.performLogin(x)
      .then((response) => {
        // do something here with the response data
      });
    

    奖励积分 保存获取构造函数依赖项并将它们直接映射到对象的额外样板......

    constructor(
        private $http: ng.IHttpService,
        private $location: ng.ILocationService,
        private $q: ng.IQService) {
      // NOT NEEDED this.qService = $q;
      // NOT NEEDED this.httpService = $http;
      // NOT NEEDED this.locationService = $location;
      this.loginResponse = new LoginResponse();
      this.serviceURL = staticURL + currentServiceName;
    }
    

    通过在参数前面添加private,它会自动将它们作为属性添加到实例中。但是它们将是它们被注入的名称......所以你必须使用this.$http而不是this.httpService

    【讨论】:

    • tnx,现在试试,Q.Promise 应该是 $q ?
    • 啊,是的,谢谢...我一直在做很多节点,我会相应地更新答案...它实际上将 ng.IPromise 作为返回类型
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-02
    • 2015-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多