how to post associative array in ionic 3 - laravel

When i try to post a data in associative array to rest api using ionic.
Only empty data receive in server side.
Is this method is correct or suggest any other method
public login(credentials) {
let apiUrl = this.urlService.apiUrl + 'oauth/access_token';
let headers = new Headers({'Content-Type' : 'application/x-www-form-urlencoded'});
let options = new RequestOptions({
headers: headers});
var postcredn=new Array();
postcredn['username'] = "karthik#abcde.in";
postcredn['password'] = "05550";
postcredn['grant_type'] = "password";
postcredn['client_id'] = "Outfit1548669";
postcredn['client_secret'] = "a10620c85033abd17716cda245";
console.log('iii'+postcredn['username'] );
return new Promise((resolve, reject) => {
this.http.post(apiUrl, postcredn, options)
.subscribe(res => {
resolve(JSON.parse(JSON.stringify(res)));
console.log('json'+ JSON.stringify(postcredn));
}, (err) => {
reject(err);
console.log(apiUrl);
});
});
}
} console.log(apiUrl);
});
});
}
}
Thanks in advance

Please rewrite following code:
First you need to create interface like:
export interface Postdata{
username: String;
password:String;
grant_type:String;
client_id: String;
client_secret: String;
}
Then import it and set its value:
var postcredn:Postdata;
postcredn={
username:'karthik#abcde.in',
password:'05550',
grant_type:'password',
client_id:'Outfit1548669',
client_secret:'a10620c85033abd17716cda245'
}
Finally post it via post method:
return new Promise((resolve, reject) => {
this.http.post(apiUrl, postcredn, options)
.subscribe(res => {
resolve(JSON.parse(JSON.stringify(res)));
console.log('json'+ JSON.stringify(postcredn));
}, (err) => {
reject(err);
console.log(apiUrl);
});
});

Associative arrays in Javascript are technically Objects and can't be instantiated via new Array(). To create one you can use any of new Object() or {}. So from the code you posted, you will define it as var postcredn=new Object(); or var postcredn={};
In your Laravel code, you can access it as you would an associative array in PHP.

Related

Cypress - unable to store response.body data into a JSON file

I've created a POST XMLHttpRequest with FormData successfully. I now need to capture it's response body and get it stored in a JSON file.
Cypress.Commands.add(
"Post_Clients",
(imagePath, imageType, attr1, attr2, attr1Val, done) => {
cy.fixture(imagePath, "binary").then(imageBin => {
Cypress.Blob.binaryStringToBlob(imageBin, imageType).then(blob => {
const xhr = new XMLHttpRequest();
xhr.withCredentials = true;
const data = new FormData();
data.set(attr1, attr1Val);
data.set(attr2, blob);
xhr.open("POST", "https://api.teamapp.myhelpling.com/admin/clients");
xhr.responseType = "json"
xhr.setRequestHeader("accept", "application/json");
xhr.setRequestHeader("access-token", accesstoken);
xhr.setRequestHeader("client", client);
xhr.setRequestHeader("expiry", expiry);
xhr.setRequestHeader("token-type", tokentype);
xhr.setRequestHeader("uid", uid);
xhr.onload = function() {
done(xhr);
};
xhr.onerror = function() {
done(xhr);
};
xhr.send(data);
});
});
}
);
it.only("API POSTing TEST", () => {
cy.Post_Clients(
"/images/clients/Golden JPEG.jpeg",
"image/jpeg",
"client[name]",
"client[client_logo_attributes][content]",
"Test Attr 1 Value is Hi!!!",
resp => {
cy.writeFile(
"cypress/fixtures/POST API OUTPUT DATA/Client.json",
resp.response
);
expect(response.status).to.eq(201);
}
);
});
Kindly note that expect(response.status).to.eq(201); assertion works well.
Following code logs the body properly in the console
cy.log("Response Body", resp.response);
console.log("Response Body", resp.response);
Response Body is: -
{"client":{"id":452,"name":"Test Attr 1 Value is Hi!!!","client_logo":{"id":543,"path":"https://api.teamapp.myhelpling.com/uploads/client_images/6279486665-1551780183.","thumb":"https://api.teamapp.myhelpling.com/uploads/client_images/thumb_6279486665-1551780183.","medium":"https://api.teamapp.myhelpling.com/uploads/client_images/medium_6279486665-1551780183.","large":"https://api.teamapp.myhelpling.com/uploads/client_images/medium_6279486665-1551780183.","filename":"blob","ratio":1.78}}}
but
cy.writeFile(
"cypress/fixtures/POST API OUTPUT DATA/Client.json",resp.response
);
doesn't save the response body in Client.JSON file.
cy.writeFile seems to not work in this code. I've verified this by
passing a JSON e.g. {"A":"B"} and that too didn't make it to the
JSON.
Thanks everyone for all you kind help. I've made it work by calling cy.writeFile inside onLoad event before triggering XHR request. Here's the code sample with some other updates that I've made for my other works: -
Cypress.Commands.add(
"Post_Bucket",
(imagePath, imageType, title, img, titleVal) => {
cy.fixture(imagePath, "binary").then(imageBin => {
Cypress.Blob.binaryStringToBlob(imageBin, imageType).then(blob => {
const xhr = new XMLHttpRequest();
const data = new FormData();
data.set(title, titleVal);
data.set(img, blob);
cy.readFile(Cypress.env("IDStore")).then(obj => {
xhr.open(
"POST",
Cypress.env("BucketPostURLPart1") +
obj.journeyID +
Cypress.env("BucketPostURLPart2"),
false
);
xhr.setRequestHeader("accept", "application/json");
xhr.setRequestHeader("access-token", accesstoken);
xhr.setRequestHeader("client", client);
xhr.setRequestHeader("expiry", expiry);
xhr.setRequestHeader("token-type", tokentype);
xhr.setRequestHeader("uid", uid);
xhr.onload = function() {
if (this.status === 201) {
cy.writeFile(
Cypress.env("BucketOutputFile"),
JSON.parse(this.responseText)
);
cy.readFile(Cypress.env("IDStore")).then(obj => {
obj.bucketID = JSON.parse(this.responseText).bucket.id;
cy.writeFile(Cypress.env("IDStore"), obj);
});
}
};
xhr.send(data);
});
});
});
}
);
This is the simple example try with this one.
cy.request('https://jsonplaceholder.cypress.io/users')
.then((response) => {
cy.writeFile('cypress/fixtures/users.json', response.body)
})

Dialogflow v2 Actions on Google response timeout

Hi I have a timeout problem to get a json response; I am using google places API to look for the closest location.
Could anyone help me with this? Thanks.
const PlaceSearch = require("./node_modules/googleplaces/lib/NearBySearch.js");
const PlaceDetailsRequest = require("./node_modules/googleplaces/lib/PlaceDetailsRequest.js");
app.intent('Ask Location', conv => {conv.ask(new Permission({context: 'To start',permissions: 'DEVICE_PRECISE_LOCATION',}));});
app.intent('geolocation.intent', (conv,params,granted) =>{
if(granted){
var coordinates = conv.device.location.coordinates;
var location = [coordinates.latitude, coordinates.longitude];
var searchParameters = {
location: location,
name:'Store Name',
radius:10000
};
var config = {
apiKey:'#####',
outputFormat:'json'
};
var placeSearch = new PlaceSearch(config.apiKey, config.outputFormat);
var placeDetailsRequest = new PlaceDetailsRequest(config.apiKey, config.outputFormat);
placeSearch(searchParameters, function (error, search_response) {
if(search_response.status === 'OK'){
placeDetailsRequest({reference: search_response.results[0].reference}, function (error, details_response) {
conv.ask(`Your closest store is at ${details_response.result.formatted_address}.`);
});
}
});
}
});
I solved the issue using a request to Google API via URL; and using a promise.
const request = require("request");
app.input("geolocation.intent", conv => {
return new Promise((resolve, reject) => {
...
request(options, (error, response, body) => {
...
if (error) {
...
reject(...);
} else {
...
resolve(...);
}
}).then(result => {
const address = result.address;
conv.ask('Your closest store is...');
}).catch(error => {
conv.close('Error in Promise');
});
});
What I learned is that in Dialogflow API v2 you need to use promises when you make a request.

Query additional API Endpoint with Axios & Vue after getting results from a different endpoint

I'm utilising the following API for a World Cup Laravel app - http://api.football-data.org/docs/v1/index.html#_fixture
This information brings me back today's fixture's as I'm using this code (config just holds my API key):
const todaysMatches = new Vue({
el: '#todaysMatches',
data: {
todaysMatches: [],
flags: []
},
methods: {
loadData: function () {
axios.get("http://api.football-data.org/v1/competitions/467/fixtures/?timeFrame=p1", config)
.then(response => {this.todaysMatches = response.data});
}
},
mounted: function () {
this.loadData();
}
});
This brings back the following data sctructure:
Inside each fixture you get an array of _links which you can see in the below screenshot:
Now, what I would like to do is query both the awayTeam api and the homeTeam api because they each have an endpoint of crestUrl which returns the country's flag.
You can see that inside my data I've set an array prop called flags so I was thinking of running additional calls inside my loadData method and populate that array for each fixture, but I don't think that's a clean way of doing it.
Can anyone suggest the best way to approach this?
I have used async/await pattern to achieve your requirement as below:
loadData: async function() {
const response = await axios.get(
"http://api.football-data.org/v1/competitions/467/fixtures/?timeFrame=p1",
config
);
this.todaysMatches = response.data;
let arr = this.todaysMatches.fixtures.map(fixture => {
const _links = fixture._links;
return [
axios.get(_links.awayTeam.href, config),
axios.get(_links.homeTeam.href, config)
];
});
arr.forEach(async item => {
const away = await item[0];
const home = await item[1];
this.flags.push({
awayFlag: away.data.crestUrl,
homeFlag: home.data.crestUrl
});
});
}
Explaination:
After fetching todaysMatches a new array arr is created which consists of promises returned by get request to the team's url [[getAwayTeamInfo, getHomeTeamInfo], [getAwayTeamInfo, getHomeTeamInfo], [getAwayTeamInfo, getHomeTeamInfo],...]
We loop through this and await on the promise to get the crestUrl
This crestUrl is pushed into flags array as an object
{
awayFlag: away.data.crestUrl,
homeFlag: home.data.crestUrl
}
Update
Adding the flag urls directly to the this.todaysMatches.fixtures array
loadData: async function() {
const response = await axios.get(
"http://api.football-data.org/v1/competitions/467/fixtures/?timeFrame=p1",
config
);
this.todaysMatches = response.data;
const fixtures = this.todaysMatches.fixtures;
let arr = fixtures.map(fixture => {
const _links = fixture._links;
return [
axios.get(_links.awayTeam.href, config),
axios.get(_links.homeTeam.href, config)
];
});
arr.forEach(async (item, index) => {
const away = await item[0];
const home = await item[1];
this.$set(fixtures, index, {
...fixtures[index],
awayFlag: away.data.crestUrl,
homeFlag: home.data.crestUrl
});
});
}

ioredis bluebird a promise was created in a handler but was not returned from it

Can someone please explain to me why i'm getting this warning Warning: a promise was created in a handler but was not returned from it when I execute the following code:
cache['deviceSlave'].getBySystemId(systemId).then(function(slavesMapping) {
// do other stuff
}).catch(function(err) {
// throw error
});
Here is the rest of the code:
var Promise = require('bluebird');
var _ = require('lodash');
var Redis = require('ioredis');
var config = require('/libs/config');
var redis = new Redis({
port: config.get('redis:port'),
host: config.get('redis:host'),
password: config.get('redis:key'),
db: 0
});
var self = this;
module.exports.getBySystemId = function(systemId) {
return new Promise(function(resolve, reject) {
var systemIds = [systemId];
self.getBySystemIds(systemIds).then(function(result) {
return resolve(_.values(result)[0]);
}).catch(function(err) {
return reject(err);
});
});
};
module.exports.getBySystemIds = function(systemIds) {
return new Promise(function(resolve, reject) {
var pipeline = redis.pipeline();
_.each(systemIds, function(systemId) {
var cacheKey = 'device_slaves:' + systemId.replace(/:/g, '');
// get through pipeline for fast retrieval
pipeline.get(cacheKey);
});
pipeline.exec(function(err, results) {
if (err) return reject(err);
else {
var mapping = {};
_.each(systemIds, function(systemId, index) {
var key = systemId;
var slaves = JSON.parse(results[index][1]);
mapping[key] = slaves;
});
return resolve(mapping);
}
});
});
};
I'm using the following libraries: ioredis & bluebird.
The code executes fine and everything just works good! I just dont like the fact I get an warning which I can not solve!
Bluebird is warning you against explicit construction here. Here is how you should write the above code:
module.exports.getBySystemId = function(systemId) {
return self.getBySystemIds([systemId]).then(result => _.values(result)[0]);
};
There is no need to wrap the promise - as promises chain :)

How do I post data using $resource using angularjs

I'm having a bit of a problem, I'm trying to do a http post request to my backend php. I'm new to angular and wanted to try the different REST method. I'm good with GET method. After this I will try UPDATE and DELETE method but for now I'm stuck on this. T__T.
Here a bit of the code in php
$data = array(
"email" => $email,
"password" => $this->input->post("password")
);
$insert_data = $this->player_registration->insert($data);
And here my factory
angular.module('myApp.services', ['ngResource'])
.factory('webService', function($resource){
var apiUrl = "http:domain.com/feed/"; //change this to web service
var factory = {};
factory.registerPlayer = function() {
return $resource( apiUrl + ':type', {type:'player'}, {
post: {method:'POST', params: {}}
});
};
factory.getPlayerByEmail = function () {
return $resource( apiUrl + ':type', {type:'player'}, {
get: {method: "GET", params: {}}
});
};
return factory;
})
And my controller
function registerController($scope, webService) {
$scope.inputs = {};
$scope.inputs.email = "testuser#domain.com";
$scope.inputs.password = "password";
var req = new webService.registerPlayer($scope.inputs);
req.save()
My app.js
angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives', 'myApp.controllers'])
The default save() in $resources is actually $save().
var req = new webService.registerPlayer($scope.inputs);
req.$save()

Resources