简体   繁体   English

角度承诺和$ http

[英]angular promise and $http

ng.module('app')
    .service('CardService', ['$http', CardService])

function CardService($http) {
    this.$http = $http;
    var self = this;

  $http.get('http://localhost:3000/db').success(function(data) {
      self.items = data;
      console.log(self.items);
  });
  console.log(self.items);
}

CardService.prototype.list = function() {
        console.log(self.items);
        return this.items;
};

and result 和结果

service.js:14 undefined service.js:14未定义

service.js:18 undefined service.js:18未定义

service.js:18 undefined service.js:18未定义

service.js:12 [Object, Object, Object] service.js:12 [Object,Object,Object]

How do I solve this problem? 我该如何解决这个问题?

The ajax call is async. Ajax调用是异步的。 It will allow the thread to move on while it waits for a response from the .get 等待.get响应时,它将允许线程继续运行。

the console.logs you are doing will then be called in this order. 您正在执行的console.logs将按此顺序调用。

  1. console.log right below your ajax call 在ajax调用下方的console.log
  2. console.log inside list prototype 列表原型内的console.log

(inside ajax success) (在ajax成功内)

  1. console.log inside list prototype 列表原型内的console.log
  2. console.log below self.items = data console.log下面self.items = data

Not the angular way, but... the prototype should used only when the list is initialized inside the ajax call. 不是成角度的方式,而是...仅当在ajax调用中初始化列表时,才应使用原型。

According to best practices, you should do all the http request related stuff to get data using factory or service. 根据最佳实践,您应该执行所有与http请求相关的工作,以使用工厂或服务获取数据。 As it is asynchronous flow, $q shall be used to handle it. 由于它是异步流,因此应使用$ q来处理它。 So your functionality would be done as given below. 因此,您的功能将按照以下说明进行。 Kindly correct me if i have misinterpreted your question. 如果我误解了你的问题,请纠正我。

app.factory('CardService',function($http,$q) {
var obj = {};

    obj.getCardServiceData = function(){
        var defer = $q.defer();
        $http.get('http://localhost:3000/db').then(function(response) {
         defer.resolve(response.data);
       },function(error){
          defer.reject(error);
       });
       return defer.promise;
    }

    return obj;

});

app.controller('YOUR CONTROLLER',function($scope,CardService){
      CardService.getCardServiceData().then(function(response){
           $scope.self = response.data;
           console.log($scope.self);
       },function(error){
           alert("There seems to be some error!");
           console.error(error);

       });
});

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

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