i´m working on an Alexa Skill with nodejs.
When I want to get a response i don´t get any message when trying to get it with response.say(value). But when trying with console.log(value) i get the right response.
alexaApp.intent("Plot", {
"slots": { "Titel": "String"},
"utterances": ["Wovon handelt {Titel}"]
},
function(request, response) {
var titel = request.slot("Titel");
geturl(titel,1).then((speech) => {
console.log(speech); //right string
response.say(speech); //nothing
});
});
Any ideas how to get it working? I´m working with promises cause of the async of node to get my requests in time.
you should use synchronous call to get request. here a woking example :
var http = require('bluebird').promisifyAll(require('request'), { multiArgs: true });
app.intent('search', {
"utterances": [
"search ",
]
},
function(request, response) {
return http.getAsync({ url: url, json: true}).spread(function(statusCodesError, result) {
console.log(result)
});
})
You do need to use an async call, and return the promise.
var http = require('bluebird').promisifyAll(require('request')
alexaApp.intent("Plot", {
"slots": { "Titel": "String"},
"utterances": ["Wovon handelt {Titel}"]
},
function(request, response) {
var titel = request.slot("Titel");
return http.getAsync(titel,1)
.then((speech) => {
return response.say(speech);
}).catch(function(err){
return response.say(err);
});
Related
I am using angular and talking to an express backend. I can retrieve data from my .get, but my .post is generating a validation error
Client-controller:
$scope.addFriend = function()
{
friendsFactory.addFriend($scope.newFriend, function (data)
{
$location.url('/friends' + data._id);
});
}
Client-factory:
factory.addFriend = function (newFriendData, callback) {
$http.post('/friends', newFriendData)
.then(function(response)
{
console.log(response.data);
//callback(response.data);
})
}
Server-route:
app.post('/friends', function (request, response) {
console.log('routes')
friends.create(request, response);
})
Server-controller:
create: function(request, response)
{
console.log('request');
var friendInstance = new Friend();
friendInstance.first_name = request.params.fname;
friendInstance.last_name = request.params.lname;
friendInstance.b_day = request.params.bday;
friendInstance.save(function(err,data)
{
if (err)
{
response.json(err);
}
else {
rewponse.json(data);
}
})
Error on console:
Object {errors: Object, message: "Friend validation failed", name: "ValidationError"}
this is most likely a mongoose error, the document that you're trying to persist does not follow the Friend schema.
I getting the data from ng-model from html->controllers->services->Factories
After saving i got response is like this
This my response
Resource {_id: "56fe5ddc414e823023576508", productcode: "101", productname:"desktops",
__v: 0, isDeleted: false…}
$promise:undefined
$resolved:true
__v:0
_id:"56fe5ddc414e823023576508"
isDeleted:false
productcode:"101"
productitems:Array[1]
productname:"desktops"
__proto__:Object
myFacory code:
factmodule.factory("DashboardItemFactory",function($resource){
var ProductItemnew=[];
ProductItemInfoResourec=$resource("http://192.168.0.194:9070/productitems/:id",
{"id": "#id","productid":"#productid"}, {update: {method: "PUT"}});
return{
addProductItemnew:function(itemslist){
var items = new ProductItemInfoResourec(itemslist);
items.$save({"id":itemslist.productid},function(respdata){
console.log(respdata)
ProductItemnew.push(respdata);
console.log("Data Saved...")
},function(respdata){
console.log("Error while saving the data");
});
},
}
})
Please help me how make the data as promise..
You need to return promise object from the factory method. Resources have $promise property which is what you need. So it could be something like this:
factmodule.factory("DashboardItemFactory", function($resource) {
var ProductItemnew = [];
ProductItemInfoResourec = $resource("http://192.168.0.194:9070/productitems/:id", {
"id": "#id",
"productid": "#productid"
}, {
update: {
method: "PUT"
}
});
return {
addProductItemnew: function(itemslist) {
var items = new ProductItemInfoResourec(itemslist);
return items.$save({ id: itemslist.productid }).$promise.then(function(respdata) {
ProductItemnew.push(respdata);
console.log("Data Saved...", respdata)
return respdata; // or return ProductItemnew;
}, function(respdata) {
console.log("Error while saving the data");
throw new Error("Error while saving the data")
});
}
}
})
Just decide what you want this promise to resolve with: either original response from save request or maybe ProductItemnew array.
it is working for me with $q
factmodule.factory("DashboardItemFactory",function($resource,$q){
var ProductItemnew=[];
ProductItemInfoResourec=$resource("http://192.168.0.194:9070/productitems/:id/:itemid",
{"id": "#id","productid":"#productid"}, {update: {method: "PUT"}});
return{
addProductItemnew:function(itemslist){
var dfr = $q.defer();
var items = new ProductItemInfoResourec(itemslist);
items.$save({"id":itemslist.productid},function(respdata){
console.log(respdata)
ProductItemnew.push(respdata);
dfr.resolve(ProductItemnew);
console.log("Data Saved...")
return dfr.promise;
},function(respdata){
console.log("Error while saving the data");
});
}
}
})
I'm using CordovaHTTP with Angular and injected the Cordova HTTP into a service. I haven't found many examples on how to implement a POST so below is what I did so far. The issue I'm having is that the post block never reaches the success or error blocks and my debug statements are not getting printed.
Does this look correct?
Calling function:
this.authenticate = function ( code, data, callback ) {
try {
// Build url
var url = o.buildServerUrl(o.loginUrl, code);
RestService.post(url, data, function(response) {
if (response.status === o.HTTP_STATUS_OK) {
...
}
callback(response);
});
}
catch(err) {
var response = o.createServerErrorResponse(o.MSG_SERVER_ERROR);
callback(response);
}
}
Service:
oApp.service( 'RestService', function( cordovaHTTP ) {
this.post = function ( url, data, callback ) {
try {
// Build url
if (o.debug) console.log('Cordova REST: '+url);
cordovaHTTP.post( url, data, {}, function(response) {
if (o.debug) console.log('Rest ok');
// Success
var response = o.processServerResponse(response);
callback(response);
}, function(response) {
if (o.debug) console.log('Response error');
var response = o.processCordovaServerResponse(response);
callback(response);
});
}
catch(err) {
var response = o.createExceptionResponse(err.message);
callback(response);
}
}
});
Im trying to publishUpdate some data from the server in order to listen for user/profile creation but im not able to listen to those events in the client using Angular. Is it possible im missing something here? Or maybe something wrong im doing?
// UserController
saveUser: function(req, res) {
User.create({name: req.param('name'), profile: {aboutMe: req.param('about'), gender: req.param('gender')}})
.exec(function(err, user) {
Profile
.findOneById(user.profile)
.exec(function(err, profile) {
profile.user = user.id;
profile.save(function(error, saved){
if (error) return res.badRequest('Error.');
if (saved) res.json(saved);
Profile.publishUpdate(saved.id, saved);
});
});
});
}
// Client Angular
$scope.send = createUser;
listenProfile();
function createUser() {
var obj = {
name: $scope.name,
about: $scope.profile.about,
gender: $scope.profile.gender
User.create(obj).then(function(data) {
console.log(data); // Data displayed correctly
}, function(error) {
console.log(error);
});
}
function listenProfile() {
io.socket.on('profile',function(data){
console.log(data); //Nothing happens?
});
};
Try changing it to a capital P:
function listenProfile() {
io.socket.on('Profile',function(data){
console.log(data); //Nothing happens?
});
};
I think that are missing "suscribe" to your model... for example
Profile.subscribe(req.socket, data);
And linked to your app via GET.
io.socket.get("/profile",function(data){
console.log(data);
});
I am using a JSONAPI compliant API, and one of the format requirements is that all data (incoming and outgoing) must be wrapped in a data object. So my request looks like:
{
"data": {
"email": "email#example.com",
"password": "pass",
"type": "sessions"
}
}
And my response looks like:
{
"data": {
"user_id": 13,
"expires": 7200,
"token": "gpKkNpSIzxrkYbQiYxc6us0yDeqRPNRb9Lo1YRMocyXnXbcwXlyedjPZi88yft3y"
}
}
In my controller, when making a new session request, I have:
$scope.signin = ->
session = new Session
email: $scope.user.email
password: $scope.user.password
session.$save()
console.log session
console.log session.token
if not session.token
alert 'Invalid Login'
else
$rootScope.session_token = session.token
$state.go 'app.dashboard'
And my Session is a factory that looks like:
angular.module('webapp').factory 'Session', [
'$resource'
($resource) ->
$resource 'http://localhost:9500/v1/sessions',
id: '#id'
,
save:
method: 'POST'
transformRequest: (data) ->
result =
data: JSON.parse JSON.stringify data
result.data.types = 'sessions'
result = JSON.stringify result
result
transformResponse: (data) ->
result = JSON.parse data
a = JSON.parse JSON.stringify result.data
console.log a
a
The request is fine. The formatting and parsing seems to work. However, the response, when I log it shows as a Resource, not Object. And session.token shows as undefined even though the server is returning valid data.
How do I modify my transformResponse to account for this?
I think what you want is to capture your Resource response with a promise:
session.$save().$promise.then(function (result) {
console.log (result);
});
May I suggest an XHR interceptor?
xhrInterceptor.js:
(function (app) {
"use strict";
function XhrInterceptor($q) {
return {
request: function requestInterceptor(config) {
var data = config.data;
if (data &&
config.method === "POST") {
config.data = {
data: data
};
}
return config || $q.when(config);
},
response: function responseInterceptor(response) {
if (typeof response === "object") {
if (response.config.method === "POST") {
response.data = response.data.data || {};
}
}
return response || $q.when(response);
}
};
}
app
.factory("app.XhrInterceptor", ["$q", XhrInterceptor]);
})(window.app);
app.js:
In with your config phase, or other initialisation logic, add the response interceptor.
app
.config(["$httpProvider", function ($httpProvider) {
$httpProvider.interceptors.push("app.XhrInterceptor");
});
Further information
XHR Interceptor in an AngularJS web app
Intercept XHR/Ajax requests with AngularJS http