【发布时间】:2018-06-18 20:56:53
【问题描述】:
总的来说,我是 angularjs 和 Web 开发的新手。 我有一个 ajax 请求,在单击按钮后会向服务器发送一些信息。当请求返回成功时,我想显示一个表示请求已成功发送的祝酒词。然而,吐司永远不会弹出,但我确实有一个控制台日志,它打印出请求已发送。为什么吐司不爆?
注意:当我尝试在 ajax 调用的成功函数之外显示 toast 时,它确实有效。
提前致谢。
这是我的代码:
(function() {
'use strict';
angular
.module('app.dashboard')
.controller('NotificationController', NotificationController);
NotificationController.$inject = ['$resource', '$http', '$state','toaster'];
function NotificationController($resource, $http, $state, toaster) {
var vm = this;
activate();
vm.alertSubmit = function() {
console.log(vm.subject);
console.log(vm.htmlContent);
const item = {
'subject':vm.subject,
'body': vm.htmlContent
};
//toaster.pop(vm.toaster.type, vm.toaster.title, vm.toaster.text); If I try this line the toast does appear.
//console.log(item);
//console.log(JSON.stringify(item));
$.ajax({
type: 'POST',
accepts: 'application/json',
url: 'api/pushnotification',
contentType: 'application/json',
data: JSON.stringify(item),
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
toaster.pop(vm.toaster.type, "Failure", "Message wasn't send.");
},
success: function (result) {
console.log(result);
toaster.pop(vm.toaster.type, vm.toaster.title, vm.toaster.text);
}
});
return false;
};
function activate() {
// the following allow to request array $resource instead of object (default)
$http
.get('api/auth')
.then(function(response) {
// assumes if ok, response is an object with some data, if not, a string with error
// customize according to your api
if (!response.data) {
$state.go('page.login');
}
else
{
var actions = {'get': {method: 'GET', isArray: true}};
vm.toaster = {
type: 'success',
title: 'Success',
text: 'Message was sent successfully.'
};
//vm.pop = function () {
// toaster.pop(vm.toaster.type, vm.toaster.title, vm.toaster.text);
//};
}
}, function() {
$state.go('page.login');
});
console.log("activate func");
}
}
})();
【问题讨论】:
-
jQuery ajax 没有与 AngularJS 框架集成。而是使用集成的 AngularJS $http 服务。只有在 AngularJS 执行上下文中应用的操作才能受益于 AngularJS 数据绑定、异常处理、属性监视等。
标签: javascript angularjs