我的服务是:
myApp.service('userService', [
'$http', '$q', '$rootScope', '$location', function($http, $q, $rootScope, $location) {
var deferred;
deferred = $q.defer();
this.initialized = deferred.promise;
this.user = {
access: false
};
this.isAuthenticated = function() {
this.user = {
first_name: 'First',
last_name: 'Last',
email: 'email@address.com',
access: 'institution'
};
return deferred.resolve();
};
}
]);
Run Code Online (Sandbox Code Playgroud)
我config通过以下方式在我的文件中调用它:
myApp.run([
'$rootScope', 'userService', function($rootScope, userService) {
return userService.isAuthenticated().then(function(response) {
if (response.data.user) {
return $rootScope.$broadcast('login', response.data);
} else {
return userService.logout();
}
});
}
]);
Run Code Online (Sandbox Code Playgroud)
但是,它抱怨说这then不是一个功能.我不回复已解决的承诺吗?
我尝试使用Angular和Bluebird的承诺:
HTML:
<body ng-app="HelloApp">
<div ng-controller="HomeController">{{name}} {{also}}</div>
</body>
Run Code Online (Sandbox Code Playgroud)
JS:
// javascript
var app = angular.module('HelloApp', []);
app.controller("HomeController", function ($scope) {
var p = Promise.delay(1000).then(function () {
$scope.name = "Bluebird!";
console.log("Here!", $scope.name);
}).then(function () {
$scope.also = "Promises";
});
$scope.name = "$q";
$scope.also = "promises";
});
window.app = app;
Run Code Online (Sandbox Code Playgroud)
[ 小提琴 ]
但是,不管我尝试了什么,它都会保持停留"$q promises"并且不会更新.除非我添加了一本$scope.$apply我宁愿避免使用的手册.
(我知道这是可能的,因为$ q会这样做)
我正在使用Bluebird 2.0,我在这里.
我正在使用angular-ui-router resolve来从服务器获取数据,然后再转到状态.有时,对服务器的请求失败,我需要通知用户有关失败的信息.如果我从控制器调用服务器,我可以在then其中调用我的通知服务,以防呼叫失败.我将调用放入服务器,resolve因为我希望后代状态在服务器启动之前等待服务器的结果.
如果对服务器的调用失败,我在哪里可以捕获错误?(我已经阅读了文档,但仍然不确定如何.另外,我正在寻找尝试这个新代码段工具的理由:).
"use strict";
angular.module('MyApp', ["ui.router"]).config([
"$stateProvider",
"$urlRouterProvider",
function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/item");
$stateProvider
.state("list", {
url: "/item",
template: '<div>{{listvm}}</div>' +
'<a ui-sref="list.detail({id:8})">go to child state and trigger resolve</a>' +
'<ui-view />',
controller: ["$scope", "$state", function($scope, $state){
$scope.listvm = { state: $state.current.name };
}]
})
.state("list.detail", {
url: "/{id}",
template: '<div>{{detailvm}}</div>',
resolve: {
data: ["$q", "$timeout", function ($q, $timeout) {
var deferred = $q.defer();
$timeout(function () {
//deferred.resolve("successful");
deferred.reject("fail"); // resolve fails …Run Code Online (Sandbox Code Playgroud)随着jQuery延迟,我以前能够像这样检查当前状态:
var defer = $.Deferred();
defer.state(); //Returns the state of the deferred, eg 'resolved'
Run Code Online (Sandbox Code Playgroud)
Angular deferreds有没有办法做同样的事情?(甚至更好的承诺)
我希望能够调用内部的功能.那么范围,为此,我用的是this.foo()的方式.但是,如果我在内部执行此操作,那么我会收到错误,因为这似乎丢失了.我能做什么?
在该代码中,这将等同于具有该对象的相同的输出这
console.log(this)
one().then(function() {
console.log(this)
})
function one() {
var deferred = $q.defer();
deferred.resolve()
return deferred.promise;
}
Run Code Online (Sandbox Code Playgroud)
这似乎都不起作用
console.log(this)
var a = this;
one().then(function(a) {
console.log(a)
})
Run Code Online (Sandbox Code Playgroud) 我想使用Promises在AngularJS中实现动态加载静态资源.问题:我在页面上有几个组件可能(或不是,取决于哪些显示,因此是动态的)需要从服务器获取静态资源.加载后,可以在整个应用程序生命周期内进行缓存.
我已经实现了这个机制,但我是Angular和Promises的新手,我想确保这是一个正确的解决方案\方法.
var data = null;
var deferredLoadData = null;
function loadDataPromise() {
if (deferredLoadData !== null)
return deferredLoadData.promise;
deferredLoadData = $q.defer();
$http.get("data.json").then(function (res) {
data = res.data;
return deferredLoadData.resolve();
}, function (res) {
return deferredLoadData.reject();
});
return deferredLoadData.promise;
}
Run Code Online (Sandbox Code Playgroud)
因此,只发出一个请求,并且对loadDataPromise()的所有下一次调用都会获得第一个承诺.它似乎适用于进展中的请求或前一段时间已经完成的请求.
但缓存Promises是一个很好的解决方案吗?
在尝试捕获承诺拒绝时,我在IE8上遇到了一个奇怪的错误(基本ngResource调用返回的承诺):
此代码使用.then(success, fail)语法:
promise.then(function(response) {
// success
},
function(response) {
// error
});
Run Code Online (Sandbox Code Playgroud)
但这个失败的.then(success).catch(fail)语法:
promise.then(function(response) {
// success
})
.catch(function(response) {
// error
});
Run Code Online (Sandbox Code Playgroud)
并且指向该.catch()行的IE错误是:
预期的标识符
难道我做错了什么 ?有人重现了吗?或者由于受限制的关键字,它是一个常见的IE8?
谢谢
internet-explorer internet-explorer-8 promise angularjs angular-promise
我试图通过迁移当前用Angular1编写的应用程序来提高我对Angular2的了解
特别令我难过的一个特点.我试图复制一个功能,其中一个调用函数等待继续,直到它调用的函数完成了一个promises循环.在有角度的一个中,我调用的函数看起来基本上是这样的:
this.processStuff = function( inputarray, parentnodeid ) {
var promises = [];
var _self = this;
angular.forEach( inputarray , function( nodeid ) {
switch ( parentnodeid )
{
case ‘AAA’ : var component = _self.doMoreStuff( nodeid, parentnodeid ); break;
case ‘BBB’ : var component = _self.doMoreStuff( nodeid, parentnodeid ); break;
case ‘CCC’ : var component = _self.doMoreStuff( nodeid, parentnodeid ); break;
default : var component = null;
}
promises.push( component );
});
return $q.all(promises);
};
Run Code Online (Sandbox Code Playgroud)
它包含一个forEach循环,它调用另一个函数(doMoreStuff),该函数也返回一个promise,它将所有返回的promises存储在一个数组中.
使用Angular1,当我在另一个函数中调用processStuff时,我可以指望系统等到processStuff完成后再进入then块中的代码.IE:
service.processStuff( arraying, …Run Code Online (Sandbox Code Playgroud) 我有一个AngularJS代码:
service.doSomething()
.then(function(result) {
//do something with the result
});
Run Code Online (Sandbox Code Playgroud)
在AngularJS 1.5.9中,当我在该.then()部分中有错误时:
service.doSomething()
.then(function(result) {
var x = null;
var y = x.y;
//do something with the result
});
Run Code Online (Sandbox Code Playgroud)
我收到明确的错误消息:
TypeError:无法读取null的属性"y"
但是在版本1.6中使用相同的代码我得到了一个不同的错误:
可能是未处理的拒绝:{}未定义
我知道这与此更改有关,通过添加.catch()块,单个解决方案非常简单:
service.doSomething()
.then(function(result) {
var x = null;
var y = x.y;
//do something with the result
})
.catch(console.error);
Run Code Online (Sandbox Code Playgroud)
现在我再次拥有我想要的东西:
TypeError:无法读取null的属性"y"
但是如何在不在.catch()每个地方添加块的情况下为整个应用程序获得相同的结果(更详细的错误)?
我测试了建议的解决方案,通过添加:
$qProvider.errorOnUnhandledRejections(false);
Run Code Online (Sandbox Code Playgroud)
但有了这种情况甚至更糟 - 我在控制台中没有任何东西!错误被某处吞没,根本没有记录.我不确定AngularJS 1.6或我的配置是否有问题.
您是否有任何想法如何从1.5.9版"恢复"日志记录行为?
编辑:
添加定制错误处理程序
.factory('$exceptionHandler', function($log) {
return function(exception, cause) {
$log.warn(exception, …Run Code Online (Sandbox Code Playgroud) javascript angularjs angular-promise angular-providers angularjs-1.6
我试图了解JavaScript中的承诺(特别是AngularJS).
我在服务中有一个函数,让我们调用它fooService,检查我们是否加载了一些数据.如果有,我只想让它返回,如果我们没有,我们需要加载数据并返回一个承诺:
this.update = function(data_loaded) {
if (data_loaded) return; // We've loaded the data, no need to update
var promise = Restangular.all('someBase').customGet('foo/bar').then(function(data) {
// Do something with the data here
}
return promise;
}
Run Code Online (Sandbox Code Playgroud)
我有另一个函数然后调用这样的update函数fooService:
fooService.update(data_loaded).then(function() {
// Do something here when update is finished
})
Run Code Online (Sandbox Code Playgroud)
我的问题是,如果我们不需要在update函数中加载数据,则不返回promise,因此.then()不会在我的其他函数中调用.该方法应该在这里 - 基本上我想立即从update()函数返回一个已解决的承诺,如果我们不需要从Restangular调用中获取数据?
angular-promise ×10
angularjs ×8
javascript ×7
promise ×7
angular ×1
bluebird ×1
jquery ×1
observable ×1
restangular ×1