我有一个全局错误处理程序,我的角度应用程序写成$http interceptor,但我想更进一步.我想要的是每次$http失败的电话(被拒绝),承诺的任何"链式"消费者应首先尝试解决错误,如果它仍然未解决(未被捕获),那么我想要全球错误处理程序接管.
用例是,我的全局错误处理程序alert box在屏幕顶部显示一个咆哮.但是我弹出了几个模态,我在那里显式处理错误,在模态本身显示错误信息.因此,基本上,这个模态控制器应该将被拒绝的承诺标记为"已处理".但由于拦截器似乎总是第一个运行$http error,我无法想出办法.
这是我的拦截器代码:
angular.module("globalErrors", ['angular-growl', 'ngAnimate'])
.factory("myHttpInterceptor", ['$q', '$log', '$location', '$rootScope', 'growl', 'growlMessages',
function ($q, $log, $location, $rootScope, growl, growlMessages) {
var numLoading = 0;
return {
request: function (config) {
if (config.showLoader !== false) {
numLoading++;
$rootScope.loading = true;
}
return config || $q.when(config)
},
response: function (response) {
if (response.config.showLoader !== false) {
numLoading--;
$rootScope.loading = numLoading > 0;
}
if(growlMessages.getAllMessages().length) { // clear messages on next …Run Code Online (Sandbox Code Playgroud) - 编辑 -
我最近遇到了一些关于承诺的奇怪的事情,但我想这可能是因为它违背了承诺的哲学.
考虑以下代码:
// Assuming Auth is just a simple lib doing http requests with promises
Auth.signup()
.then(succCall, errCall)
.then(loginSucc, loginErr)
// My callbacks here
function succCall (){
// OK, send second promise
console.log('succCall');
return Auth.login();
}
function errCall(){
// I do some things here and now
// I want to break out from here
console.log('errCall');
}
function loginSucc(){
// This is the callback of the login method when it went OK
// I want to enter here …Run Code Online (Sandbox Code Playgroud) 由于AngularJS中的success()和error()函数已弃用,我正在更新我的代码,将其替换为then().现在根据我的理解,这两段代码的行为应该相同:
$http
.get(/* some params */)
.success(function() {
// success cases here
})
.error(function() {
// error cases here
});
Run Code Online (Sandbox Code Playgroud)
和
$http
.get(/* some params */)
.then(function() {
// success cases here
}, function() {
// error cases here
});
Run Code Online (Sandbox Code Playgroud)
但在某些情况下,我会得到不同的行为.你能否向我解释为什么会发生这种情况,更重要的是,保证使用then()函数的相同行为的方法是什么?
虽然我正在使用AngularJS中的HTTP promise对象,但我没有一个明确的概念,即HTTP承诺对象实际上是什么,以及AngularJS中HTTP promise对象和传统对象之间的区别是什么!
请问有人解释一下吗?
我想用来$q.when()包装一些非承诺的回调.但是,我无法弄清楚如何在回调中解决承诺.我在匿名函数内部做什么强迫$q.when()我解释?
promises = $q.when(
notAPromise(
// this resolves the promise, but does not pass the return value vvv
function success(res) { return "Special reason"; },
function failure(res) { return $q.reject('failure'); }
)
);
promises.then(
// I want success == "Special reason" from ^^^
function(success){ console.log("Success: " + success); },
function(failure){ console.log("I can reject easily enough"); }
);
Run Code Online (Sandbox Code Playgroud)
我想复制的功能是这样的:
promises = function(){
var deferred = $q.defer();
notAPromise(
function success(res) { deferred.resolve("Special reason"); },
function failure(res) { deferred.reject('failure'); …Run Code Online (Sandbox Code Playgroud) 我正在尝试测试我构建的服务,该服务使用Angular的$ q Promise实现.我正在使用Karma,Mocha,Chai,Sinon,Sinon Chai和Chai的组合作为承诺.
我写的所有测试和返回的承诺都是通过但拒绝或使用的$q.all([ ... ]).我已经尝试了所有我能想到的但是我似乎无法找到问题所在.
以下是我正在测试的超薄版本:
"use strict";
describe("Promise", function () {
var $rootScope,
$scope,
$q;
beforeEach(angular.mock.inject(function (_$rootScope_, _$q_) {
$rootScope = _$rootScope_;
$q = _$q_;
$scope = $rootScope.$new();
}));
afterEach(function () {
$scope.$apply();
});
it("should resolve promise and eventually return", function () {
var defer = $q.defer();
defer.resolve("incredible, this doesn't work at all");
return defer.promise.should.eventually.deep.equal("incredible, this doesn't work at all");
});
it("should resolve promises as expected", function () {
var fst = $q.defer(),
snd …Run Code Online (Sandbox Code Playgroud) 观看了很多Egghead.io视频,我注意到一个常见的模式是返回自定义承诺并在回调中解决它.
.factory('myFact', function($q, $http) {
return {
getData: function() {
var deferred = $q.defer();
$http.get('/path/to/api')
.success(function(data) {
deferred.resolve(data);
});
return deferred.promise;
}
};
});
Run Code Online (Sandbox Code Playgroud)
我通常会这样写:
.factory('myFact', function($http) {
return {
getData: function() {
return $http.get('/path/to/api')
.then(function(res) {
return res.data;
});
}
};
});
Run Code Online (Sandbox Code Playgroud)
返回$q.defer()承诺而不是$http承诺是否有任何好处?这些方法与我相同.
我正在尝试创建一个服务来获取json并将其传递给我homeCtrl我可以获取数据但是当它传递给我的homeCtrl它总是返回undefined.我卡住了.
我的服务:
var myService = angular.module("xo").factory("myService", ['$http', function($http){
return{
getResponders: (function(response){
$http.get('myUrl').then(function(response){
console.log("coming from servicejs", response.data);
});
})()
};
return myService;
}
]);
Run Code Online (Sandbox Code Playgroud)
我的家庭控制器:
var homeCtrl = angular.module("xo").controller("homeCtrl", ["$rootScope", "$scope", "$http", "myService",
function ($rootScope, $scope, $http, myService) {
$scope.goData = function(){
$scope.gotData = myService.getResponders;
};
console.log("my service is running", $scope.goData, myService);
}]);
Run Code Online (Sandbox Code Playgroud) angularjs angularjs-service angularjs-factory angularjs-http angular-promise
您好,即时通讯使用angular 6使用以下代码调用rest api。我试图使代码与async-await函数同步。但是缺少什么
async save() {
if (this.changedRecords.length !== 0) {
this.post('/api/devices/update-devices', this.changedRecords).
then(x => { console.log("change"); console.log(`Resolved: ${x}`) });
}
if (this.newRecords.length !== 0) {
this.post('/api/devices/new-devices', this.newRecords).
then(x => { console.log("new"); console.log(`Resolved: ${x}`) });
}
if (this.deletedRecords != null) {
this.post('/api/devices/delete-devices', this.deletedRecords).
then(x => { console.log("deleted"); console.log(`Resolved: ${x}`) });
}
}
async post(url: string, list: DboDevice[]) {
var result;
if (list.length !== 0) {
await this.http.post(url, list).subscribe(result => {
result = true;
}, error => {
console.error(error);
result = …Run Code Online (Sandbox Code Playgroud) 从这里:https ://stackoverflow.com/a/40135509/462608
首先,这个答案描述了 Observables 如何有助于防止向服务器发出相同的重复请求,以及我们如何在多个请求之间暂停,以便服务器不会过载。
他们说:
就我在 Angular 中使用 Http 而言,我同意在正常用例中使用 Observable 与 Promise 没有太大区别。这些优点在实践中都没有真正相关。希望我将来能看到一些高级用例:)
我在这里理解的是,当使用 Http 时,Observables 的好处并不真正相关。
为什么会这样?Http在这种情况下扮演什么角色呢?
我必须研究什么主题才能理解 Http 在这里的作用?
angular-promise ×10
angularjs ×8
javascript ×5
angular ×2
angular-http ×2
promise ×2
rxjs ×2
angular6 ×1
async-await ×1
http ×1
observable ×1
unit-testing ×1