相关疑难解决方法(0)

什么是明确的承诺构建反模式,我该如何避免它?

我编写的代码看起来像:

function getStuffDone(param) {           | function getStuffDone(param) {
    var d = Q.defer(); /* or $q.defer */ |     return new Promise(function(resolve, reject) {
    // or = new $.Deferred() etc.        |     // using a promise constructor
    myPromiseFn(param+1)                 |         myPromiseFn(param+1)
    .then(function(val) { /* or .done */ |         .then(function(val) {
        d.resolve(val);                  |             resolve(val);
    }).catch(function(err) { /* .fail */ |         }).catch(function(err) {
        d.reject(err);                   |             reject(err);
    });                                  |         });
    return d.promise; /* or promise() */ |     });
}                                        | }
Run Code Online (Sandbox Code Playgroud)

有人告诉我这个被称为" 延迟反模式 "或" Promise构造函数反模式 ",这个代码有什么不好,为什么这被称为 …

javascript promise q bluebird es6-promise

479
推荐指数
3
解决办法
7万
查看次数

为什么找不到我的json文件?

我的asp.net项目中的Content文件夹中有一个json文件:

<projectName>
    \Content
        NBCCJr.json
Run Code Online (Sandbox Code Playgroud)

...以及访问它的代码:

$.getJSON('~/Content/NBCCJr.json', function (data) {
    $.each(data, function(i, dataPoint) {
        // Bla
      });
  });
)
Run Code Online (Sandbox Code Playgroud)

......但是在调用代码时没有任何反应; 浏览器控制台说:"无法加载资源:服务器响应状态为404(未找到)"

为什么没找到?是不是"tilde whack filename"文件的正确路由?

UPDATE

我也向后试了"whacks":

$.getJSON('~\Content\NBCCJr.json', function (data) {
Run Code Online (Sandbox Code Playgroud)

...并得到相同的结果(" 无法加载资源:服务器响应状态为404(未找到) ")

更新2

然后我尝试了这样一个前所未有的打击:

$.getJSON('Content/NBCCJr.json', function (data) {
Run Code Online (Sandbox Code Playgroud)

...我在控制台中收到了这个含糊不清的消息:

*GET http://localhost:9702/Content/NBCCJr.json 404 (Not Found) jquery.js:8724
XHR finished loading: "http://localhost:9702/Content/NBCCJr.json".*
Run Code Online (Sandbox Code Playgroud)

所以它还没有找到并且还没有加载?

更新3

当我尝试通过更改以下内容导航到浏览器中的文件时:

http://localhost:9702/Default.cshtml
Run Code Online (Sandbox Code Playgroud)

...至:

http://localhost:9702/Content/NBCCJr.json
Run Code Online (Sandbox Code Playgroud)

我从Vint Cerf,Tim Berners-Lee和/或Al Gore那里获得了一条信息丰富的WSOD消息说:

HTTP错误404.3 - 未找到由于扩展配置,无法提供您请求的页面.如果页面是脚本,请添加处理程序.如果要下载文件,请添加MIME映射.

更新4

感谢JAM,它现在正在运作.

我不得不将其添加到Web.Config:

  <system.webServer>
    <staticContent>
      <mimeMap fileExtension=".json" mimeType="application/json" />
    </staticContent>
  </system.webServer>
Run Code Online (Sandbox Code Playgroud)

asp.net jquery json google-chrome-devtools

84
推荐指数
2
解决办法
7万
查看次数

如何通过AngularJS路由保存数据?

我是AngularJS的新手,我正在尝试为自己构建一个简单的小应用程序.我有正在获取的应用程序的JSON数据$resource,并且这些数据应该在多个视图/路由中相同.但是,当我转到新路径时,JSON数据(存储为$scope.data)不再可用于新视图.如何将此数据传递到新视图而不需要其他提取?(教程电话目录应用程序每次从我所知道的内容中重新获取此数据.)

据我所知,$rootScope可以做到这一点,但似乎总是不赞成.如果这没有多大意义,我道歉; 我非常喜欢在这里潜水.

json scope angularjs

15
推荐指数
1
解决办法
1万
查看次数

Angular.JS触发两个异步服务调用,然后在两个完成后执行操作

我还在围绕Angular.JS缠绕我的大脑.

我有两个独立的$ http调用,从远程Web服务检索数据.我有一个动作,我想在两个服务调用完成后启动.

  1. 第一个服务调用将填充$ scope.model
  2. 第二个服务调用,修改$ scope.model中的数据(它添加了一些在视图中呈现的计数器属性)

另一个独特的要求是,最终将使用$ scope.model在控制器外部调用和更新第二个服务调用.这是一个通知消息泵.

我猜我将使用promises $ q和可能的$ service,但我不确定在一些最佳实践之后从哪里开始这样的事情.

我知道这听起来不像异步调用在这里是合适的,因为我的例子可以通过同步它来简化它.但是,第二个服务调用是一个通知更新程序,因此它将不断轮询到服务器(最终将使用websocket).

这是我在这个应用程序中看到的常见模式.

angularjs

14
推荐指数
1
解决办法
9687
查看次数

将已解决的承诺注入服务中

在设置依赖于该信息的一堆服务之前,我需要从服务器获取一些信息(模式).

我的服务器提供了一个定义模型各种属性的模式.在我的角度代码中,我有一个获取此架构的服务:

services.factory('schema', function($q, $http) {
    var deferred = $q.defer();
        $http.get('schema/').then(function(response) {
        schema = // some function of response.data
        deferred.resolve(schema);
    }, function() {
        deferred.reject('There was a problem fetching the schema');
    }); 
        return deferred.promise;
});
Run Code Online (Sandbox Code Playgroud)

我想将架构对象而不是promise作为注入依赖于架构的其他服务.$ routeProvider允许我们为控制器执行此操作:

app.config(function($routeProvider) {
    $routeProvider.
        when('/', {
            controller: 'SomeCtrl',
            resolve: {
                schema: 'schema'
            },
            ...
        });
});
Run Code Online (Sandbox Code Playgroud)

这允许我像这样定义SomeCtrl:

controllers.controller('SomeCtrl', function($scope, schema) {
    // schema is an object
    ...
});
Run Code Online (Sandbox Code Playgroud)

但对于服务,我必须这样做:

services.factory('SomeService', function(schema) {
    // schema is a promise
    schema.then(function(schema) {
        ...
    });
});
Run Code Online (Sandbox Code Playgroud)

有什么方法可以做到这一点吗?

javascript angularjs angular-promise

12
推荐指数
2
解决办法
3486
查看次数

在AngularJS控制器之间共享数据,但共享数据来自Ajax调用

我已经想出如何在下面的设计示例中使用共享服务在两个AngularJS控制器之间共享数据:

(功能小提琴)

var app = angular.module('myApp', []);

app.factory('UserData', function() {
    var data = {foo: 'bar'};

    return {
        getData: function() {
            console.log('getData');
            return data;
        },
        setData: function(newData) {
            data = newData;
        }
    };
});

function MainCtrl($scope, UserData) {
    console.log('MainCtrl');
    console.log(UserData.getData());
}
MainCtrl.$inject = ['$scope', 'UserData'];

function JobListCtrl($scope, UserData) {
    console.log('JobListCtrl');
    console.log(UserData.getData());
}
JobListCtrl.$inject = ['$scope', 'UserData'];
Run Code Online (Sandbox Code Playgroud)

我的问题是我希望保留的数据UserData来自Ajax调用(可能是使用$http).

我尝试在UserData工厂函数中执行Ajax调用,但是,因为它是异步运行的,MainCtrl并且JobListCtrlUserData服务实际上有任何数据之前执行.

有人可以给我一些关于如何设置它的方向吗?

javascript angularjs

11
推荐指数
1
解决办法
6891
查看次数

AngularJS服务存储$ http结果以防止重新生成---有更好的方法吗?

设置:我希望有一个服务,多个控制器可以查询使用$ http提取的数据.最初的解决方案是使用此处建议的promises .

问题:每次控制器查询服务时,服务都会返回$ http保证,从而导致多次查询只是从远程服务器中反复提取相同的数据.

解决方案:服务函数返回数据或下面的承诺.并由控制器进行相应的检查和操作.

app.factory('myService', function($http) {
    var items = [];
    var myService = {
        getItems: function() {
            // if items has content, return items; otherwise, return promise.
            if (items.length > 0) {
                return items;
            } else {     
                var promise = $http.get('test.json').then(function (response) {
                    // fill up items with result, so next query just returns items.
                    for(var i=0;i<response.data.length;i++){
                        items.push(response.data[i]);
                    }
                    return items;
                });
                // Return the promise to the controller
                return promise;
            } …
Run Code Online (Sandbox Code Playgroud)

angularjs angular-http angular-services

7
推荐指数
1
解决办法
3098
查看次数

从Angular工厂的HTTP返回响应数据

.factory('Api', function($http) {
         var API = "http://127.0.0.1:4567/";
         return {
             get: function(method) {
                 return $http.get(API + method).success(function(result) {
                     return result;
                 });
             }
         }
     }
Run Code Online (Sandbox Code Playgroud)

然后

console.log(Api.get("MAppData"));
Run Code Online (Sandbox Code Playgroud)

返回

Object {then: function, success: function, error: function}
Run Code Online (Sandbox Code Playgroud)

为什么不返回结果(响应数据)?

factory angularjs

5
推荐指数
1
解决办法
2万
查看次数

清除AngularJs中的服务数据

我正在尝试将数据存储在我的服务中,类似于以下答案:

在服务中处理$ http响应

app.factory('myService', function($http) {
  var promise;
  var myService = {
    async: function() {
      if ( !promise ) {
        // $http returns a promise, which has a then function, which also returns a promise
        promise = $http.get('test.json').then(function (response) {
          // The then function here is an opportunity to modify the response
          console.log(response);
          // The return value gets picked up by the then in the controller.
          return response.data;
        });
      }
      // Return the promise to the controller
      return promise;
    } …

clear logout angularjs angular-seed

5
推荐指数
1
解决办法
4540
查看次数

更新控制器外部的角度模型

我正在完成Angular教程,并做了很多阅读.但是,我无法找到这个问题的答案.或者,我可能会错误地思考它,我希望有人可以帮助我!

很简单的例子:

var phones = [
    {"name": "Nexus S",
     "snippet": "Fast just got faster with Nexus S.",
     "age": 0},
    {"name": "Motorola XOOM™ with Wi-Fi",
     "snippet": "The Next, Next Generation tablet.",
     "age": 1},
    {"name": "MOTOROLA XOOM™",
     "snippet": "The Next, Next Generation tablet.",
     "age": 2}
];

function PhoneListCtrl($scope) {
  $scope.phones = phones;
  $scope.orderProp = 'age';
}
Run Code Online (Sandbox Code Playgroud)

我上面所代表的是一个来自该控制器外部的数据源.我有一个现有的缓存功能,可以根据新数据的需要对服务器进行XHR.

让我们说模型然后改变:

phones[3] = {"name": "Something new from the server",
         "snippet": "Here is some new incoming data",
         "age": 5};
Run Code Online (Sandbox Code Playgroud)

如何告诉Angular PhoneListCtrl控制器模型已更新?如果您自己测试并更新数组,Angular不会知道更改,因此不会更新DOM.

我知道这项$http服务,但在我目前的架构中,我不能在控制器中使用$ http来获取数据 …

javascript xmlhttprequest angularjs

3
推荐指数
1
解决办法
7816
查看次数

不想在控制器中公开$ http

相关问题,有关业务处理$ HTTP,但我想稍微详细说明.我希望我的控制器能够使用类似于Angular $ http API的API执行服务调用:

$scope.login = function(user) {
  securityService.login(user).success(function(data) {
    $scope.data = data;
  }).error(function(data) {
    $scope.error = data;
  });
};
Run Code Online (Sandbox Code Playgroud)

这是一个很好的可读API.从表面上看,我在服务API中需要做的就是:

return {
  name : 'User Service',
  login : function(user) {
    return $http.post("/api/login", user);
  }
};
Run Code Online (Sandbox Code Playgroud)

太棒了,它回报了承诺successerror消息随之而来.但是......如果我想处理服务中的成功和失败案例怎么办?我想维护漂亮,可读的服务API.在这种情况下,也许我想保留用户,以便我可以公开像securityService.currentUser()`securityService.isLoggedIn()'这样的方法.

我尝试了$http.post().then(...)promise API,但那些返回整个HTTP响应.同样,我想将HTTP与服务隔离开来,并维护一个类似的具体回调API.

javascript angularjs

2
推荐指数
1
解决办法
166
查看次数

Angularjs; 在服务中使用$ http返回引用而不是实际数据

我在Angularjs中使用的服务指令不是工厂,我需要将json文件填充到局部变量;

/* Contains projects on the town */
leMaireServicess.service('cityService', function($http) {

    // JSON regions and cities loader
    this.cities = [];

    // initCities 
    this.initCities = function() {
        this.cities = $http.get('data/census/cities.js').success(function(data) {
            return data;
        });
        return this.cities;
    };

    // Get city info
    this.getCity = function() {
        return this.cities;
    };
});
Run Code Online (Sandbox Code Playgroud)

在我的控制器中我有

// Saved game controller
leMaireControllers.controller('GameCoreCtrl', function($scope, cityService) {

    /* Control the town project slides */
    cityService.initCities();
    $scope.city = cityService.getCity();

    console.log($scope.city);
});
Run Code Online (Sandbox Code Playgroud)

但它没有返回实际数据,而是返回;

Object {then: function, catch: function, finally: function, …
Run Code Online (Sandbox Code Playgroud)

object this angularjs angularjs-scope

2
推荐指数
1
解决办法
5098
查看次数