[英]Toaster doesn't appear after ajax returns success
一般來說,我對angularjs和Web開發是陌生的。 我有一個ajax請求,單擊按鈕后,該請求會將一些信息發送到服務器。 當請求返回成功時,我想顯示一個祝酒詞,表明請求已成功發送。 但是,該吐司從來沒有彈出,但我確實有一個控制台日志,該日志確實打印了已發送請求。 為什么吐司不彈出?
注意:當我嘗試在ajax調用的成功功能之外展示敬酒時,它確實起作用。
提前致謝。
這是我的代碼:
(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");
}
}
})();
正如@georgeawg正確建議的那樣,您可以使用$ http服務:
$http.post('/someUrl', data, config).then(successCallback, errorCallback);
並將您的代碼修改為:
$http.post({
'api/pushnotification', // Post URL
JSON.stringify(item), // Data to be sent
contentType: 'application/json' // Header Config
}).then(
// successCallback
function (result) {
console.log(result);
toaster.pop(vm.toaster.type, vm.toaster.title, vm.toaster.text);
},
// errorCallback
function (errorThrown) {
alert(errorThrown);
toaster.pop(vm.toaster.type, "Failure", "Message wasn't send.");
},
);
而不是您的代碼:
$.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);
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.