I have the big problem. I want to display this json, but returning undefined value.
{"StatusCode":0,"StatusMessage":"OK","StatusDescription":{ "datas": [
{"sensor_serial":"SensorSerial1", "id":"11E807676E3F30B5"},
{"sensor_serial":"sensorserial2", "id":"11E807679D82841L"},
{"sensor_serial":"sensorserial3", "id":"11E80767A5CD2820"} ]
,"home_id":"11E80768K", "active":0, "homebox_id":"11E8076792BD0164J",
"date_created":"2018-02-01T15:55:54.000Z", "date_modified":null,
"serial_number":"serialn1", "user_id":"3"} }
I use this code in service.ts
public getHomeboxPById(id: string): Observable<HomeboxP> {
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let urlSearchParams = new URLSearchParams();
urlSearchParams.append('home_id', id);
urlSearchParams.append('token', this.auth.getCurrentUser().token);
let body = urlSearchParams.toString();
return this.http.post(Api.getUrl(Api.URLS.getHomeboxPById), body, {
headers: headers
})
.map((response: Response) => {
let res = response.json();
if (res.StatusCode === 0) {
return new HomeboxP(res.StatusDescription[0]);
} else if (res.StatusCode === 1) {
this.auth.logout();
} else {
return new HomeboxP(null);
}
});
}
In ts code I call this method getHomeboxPById, like this
editHomeboxPForm: FormGroup;
homeboxp: HomeboxP;
this.editHomeboxPForm = this.fb.group({
'homebox_id': new FormControl('', Validators.required)
});
}
populateFormHomeboxP() {
this.activatedRoute.params.subscribe(
params => {
this.ws.getHomeboxPById(params['id']).subscribe(
homeboxp => {
console.log(homeboxp); // display undefined
this.homeboxp = homeboxp;
this.editHomeboxPForm.controls['homebox_id'].setValue(homeboxp.homebox_id);
}
);
}
);
}
Please, can you help me, why doesn't work?
{"StatusCode":0,"StatusMessage":"OK","StatusDescription":{ "datas": [
{"sensor_serial":"SensorSerial1", "id":"11E807676E3F30B5"},
{"sensor_serial":"sensorserial2", "id":"11E807679D82841L"},
{"sensor_serial":"sensorserial3", "id":"11E80767A5CD2820"} ]
,"home_id":"11E80768K", "active":0, "homebox_id":"11E8076792BD0164J",
"date_created":"2018-02-01T15:55:54.000Z", "date_modified":null,
"serial_number":"serialn1", "user_id":"3"} }
If this is the response of
this.http.post(Api.getUrl(Api.URLS.getHomeboxPById)
Then issue is res.StatusDescription[0] , it should be res.StatusDescription like :
new HomeboxP(res.StatusDescription);
Related
I have a JSON POST that I'm sending from my Flutter app as soon in the below code:
// class connecting value from the textfield to database with json
class LoginProfile {
int id;
String CardNumber;
String ExpiryDate;
String ExpiryYear;
String VerifyCode;
LoginProfile({this.id = 0,this.CardNumber
,this.ExpiryDate,this.ExpiryYear});
factory LoginProfile.fromJson(Map<String, dynamic> map) {
return LoginProfile(
id: map["id"],
CardNumber: map["CardNumber"],ExpiryDate: map["ExpiryDate"],ExpiryYear: map["ExpiryYear"]
);
}
Map<String, dynamic> toJson() {
return {"id": id,"CardNumber": CardNumber
,"ExpiryDate": ExpiryDate,"ExpiryYear": ExpiryYear};
}
#override
String toString() {
return 'Profile{id: $id, "CardNumber": CardNumber
,"ExpiryDate": ExpiryDate,"ExpiryYear": ExpiryYear}';
}
}
Future<bool> createProfile(LoginProfile data) async {
response = await client.post(
"$baseUrl",
headers: {'Content-Type': 'application/json; charset=UTF-8'},
body: loginProfileToJson(data),
);
if (response.statusCode == 201) {
return true;
} else {
print(response.body);
}
}
I am meant POST my JSON as below:
{
"Registration": {
"CardNumber":"5105105105105100",
"ExpiryDate":"11",
"ExpiryYear":"2023",
"VerifyCode":"123"
}
}
For some reason, I'm unable to make this work and I need to POST "Registration" as the object like it looks above.
Try with jsonEncode
Future<bool> createProfile(LoginProfile data) async {
response = await client.post(
"$baseUrl",
headers: {'Content-Type': 'application/json; charset=UTF-8'},
body: jsonEncode(loginProfileToJson(data)),
);
if (response.statusCode == 201 || response.statusCode == 200) {
return true;
} else {
print(response.body);
}
I am trying to append the new object in the for loop to the request JSON.
this is not working :
setCapabilities('default',['1','2','3'])
export function
setCapabilities(kaiId:number|"default"|"defaultLeft"|"defaultRight",capabilitiesArr:string[]){
var request:object = {
type:'setCapabilities',
kaiId:kaiId
};
capabilitiesArr.forEach(element => {
var obj = {
element:true
}
console.log(obj)
});
}
This is also not working :
export function setCapabilities(kaiId:number|"default"|"defaultLeft"|"defaultRight",capabilitiesArr:string[]){
var request:object = {
type:'setCapabilities',
kaiId:kaiId
};
capabilitiesArr.forEach(element => {
var obj[element]=true
console.log(obj)
});
}
I want the output to be as :
console.log(request)
{
type:'setCapabilities',
kaiId:'default',
'1':true,
'2':true,
'3':true
}
I've updated the code in javascript for browser to run the code snippet, but you can convert it to typescript for your use
function setCapabilities(kaiId, capabilitiesArr) {
var request = {
type: 'setCapabilities',
kaiId: kaiId
}
var obj = Object.assign({}, request)
capabilitiesArr.forEach(element => {
obj[element] = true
});
console.log(obj)
}
setCapabilities('default',['1','2','3'])
In typescript use below code
function setCapabilities(kaiId:number|"default"|"defaultLeft"|"defaultRight",capabilitiesArr:string[]) {
var request:object = {
type: 'setCapabilities',
kaiId: kaiId
}
var obj = {...request}
capabilitiesArr.forEach(element => {
obj[element] = true
});
console.log(obj)
}
i can't access to a key of a json response from a restful web service.
{"_body":"{\"values\": {\"user_id\":\"1\",\"name\":\"fred test\",\"email\":\"fred#test.test\",\"username\":\"fredtest\",\"token\":\"d5f66a06ec809d70d0c52842df8dc0011d7d1ad0f2d56f50d3123da17a2489fe\"}}","status":200,"ok":true,"statusText":"OK","headers":{"pragma":["no-cache"],"content-type":["text/html;charset=UTF-8"],"cache-control":["no-store"," no-cache"," must-revalidate"],"expires":["Thu"," 19 Nov 1981 08:52:00 GMT"]},"type":2,"url":"http://localhost/PHP-Slim-Restful/api/login"}
I would like to acces to 'values' in this function: (this.responseData.values)
login(){
console.log('login'+ this.userData);
// Your app login API web service call triggers
this.authService.postData(this.userData,'login').then((result) => {
this.responseData = result;
console.log('userdata : '+ temp);
if(this.responseData.values){
console.log('response: ' + this.responseData);
localStorage.setItem('userData', JSON.stringify(this.responseData));
this.navCtrl.push(TabsPage);
}
else{
this.showToastWithCloseButton()
}
}, (err) => {
console.log('erreur : '+err);
});
}
I have an error undifined!
Can you help me?
I have used Observable to return json data and using the subscribe function in my method and using response.json() to convert the JSON reponse from RESTful webservices.
My component method,
import {Http, Headers, Response, RequestOptions} from '#angular/http';
import {Observable} from 'rxjs/Rx';
var response = this.service.post('deleteUserDetails/'+this.selectedUserId, null);
response.subscribe((res) => {
var response = res.json();
});
Service Post method,
post(url: string, data : any): Observable<any> {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let options = new RequestOptions({ headers: headers});
return this.http.post(url, data,{headers: headers});
}
I think this might be helpful for your query.
You can make a for in your JSON and access the return values of your post. Something like that.
"this.responseData = result.json();" -> Return JSON. Make a for.
Example:
public postData(data, url: string) {
this.http.post(url, data).toPromise().then(res => {
let responseData = res.json();
if (responseData) {
for (var item of responseData) {
//Implments
}
}
}, (err) => {
});
}
I am learning Angular 2 and have an interesting issue. I am using json-server to mock my service calls and retrieve works well. However I have issues with Create and Update.
I am using a basic model called notification which looks like so:-
export class NotificationModel {
constructor(
public id: number,
public name: string,
public description: string
){}
}
and here's my basic functions nothing too strange here!
createNotification(notification : NotificationModel) {
return this._http.post('http://{myurl}/notifications', JSON.stringify(notification))
.map(res => res.json());
}
updateNotification(notification : NotificationModel) {
return this._http.put('http://{myurl}/notifications/' + notification.id, JSON.stringify(notification))
.map(res => res.json());
}
When I try to pass in simple test values I instead get the following:-
The create generates a 9 character alphanumeric value for id and nothing in the other fields.
Here's my object:-
{"id":5,"name":"NEW NOTIFICATION","description":"NEW NOTIFICATION DESCRIPTION"}
UPDATE:- Here's what it creates
{
"id": "rkxCLjZLx"
}
The update blanks out the other two fields and just keeps the id field.
Here's my object
{"id":"3","name":"Notification 3","description":"UPDATE DESCRIPTION"}
UPDATE:- Here's the record after update
{
"id": "3"
}
Is this a json-server issue or is there something obvious that I'm doing wrong?
UPDATE
Here's the functions I use to call my service
addNotification(notification : NotificationModel) {
this._notificationService.createNotification(new NotificationModel(5,
'NEW NOTIFICATION', 'NEW NOTIFICATION DESCRIPTION')).subscribe(
data => {
// refresh the list
this._notificationService.getNotifications().subscribe(res => {
this.notifications = res;
}
);
return true;
},
error => {
console.error("Error adding notification!");
return Observable.throw(error);
}
);
}
updateNotification(notification : NotificationModel) {
notification.description = 'UPDATE DESCRIPTION';
this._notificationService.updateNotification(notification).subscribe(
data => {
// refresh the list
this._notificationService.getNotifications().subscribe(res => {
this.notifications = res;
}
);
return true;
},
error => {
console.error("Error updating notification!");
return Observable.throw(error);
}
);
}
Found my issue!
I wasn't setting the content type anywhere! By updating my PUT and POST requests like so it now works as expected.
createNotification(notification : NotificationModel) {
let body = JSON.stringify(notification);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this._http.post(this.serviceURL, body, options)
.map(res => res.json());
}
updateNotification(notification : NotificationModel) {
let body = JSON.stringify(notification);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this._http.put(this.serviceURL + '/' + notification.id, body, options)
.map(res => res.json());
}
How to handle multipart/form-data with serverless-framework? v.0.5.6
Just tried this:
"requestTemplates": {
"multipart/form-data": {
"httpMethod": "$context.httpMethod",
"body": "$input.json('$')",
"queryParams": "$input.params().querystring",
"headerParams": "$input.params().header",
"headerParamNames": "$input.params().header.keySet()",
"contentTypeValue": "$input.params().header.get('Content-Type')"
},
"application/json": {
"httpMethod": "$context.httpMethod",
"body": "$input.json('$')",
"queryParams": "$input.params().querystring",
"headerParams": "$input.params().header",
"headerParamNames": "$input.params().header.keySet()",
"contentTypeValue": "$input.params().header.get('Content-Type')"
}
}
action.js:
export function respond(event, cb) {
var form = new formidable.IncomingForm();
form.parse(event, function(err, fields, files) {
if (err == null) {
var response = {
status: "true",
data: fields,
error: []
};
return cb(null, response);
} else {
console.log(err);
return cb(null, ApiErrors.errors(402, err['message'] + fields));
}
});
}
But got an error: errorMessage = "Cannot read property 'content-length' of undefined";
I've got this working with serverless by emulating http.ClientRequest and using a form parser tool like formidable.
I'm using lambda-proxy for the API Gateway event configuration.
const Stream = require('stream').Readable;
const Formidable = require('formidable');
module.exports.upload = ( e, ctx, cb ) => {
let form = new Formidable.IncomingForm();
let stream = new Stream();
stream.push( e.body );
stream.push( null );
// NOTE: You'll likely want to toLowerCase() at least 'Content-Type' header key
stream.headers = e.headers;
form.parse( stream, (err, fields, files) => {
// Work with your parsed form results here.
});
}
Well, I couldnt make it as multipart/form-data, so I used base64 string.
action.js:
export function respond(event, cb) {
//console.log('Received event:', JSON.stringify(event, null, 2));
var key = new Date().toISOString().substr(0, 10) + '/' + String(Date.now());
var contentType = event.body["data"].substr(0, event.body["data"].indexOf(';'));
if (!contentType.match(/(\.|\/)(gif|jpe?g|png)$/i)) {
return cb(null, 'invalid content type, gif, jpg, and png supported');
}
var data = new Buffer(event.body["data"].replace(/^image\/\w+;base64,/, ''),'base64');
var params = {
Bucket: 'your-bucket',
Key: key,
Body: data,
ContentEncoding: 'base64',
ContentType: contentType,
ACL: 'public-read'
};
s3.upload(params, function (err, data) {
if (err) {
console.log(err);
return cb(null, ApiErrors.errors(402, err['message']));
} else {
var response = {
status: "true",
data: {
url: urlPrefix + key
},
error: []
};
return cb(null, response);
}
});
}
RequestTemplate:
"requestTemplates": {
"application/json": {
"httpMethod": "$context.httpMethod",
"body": "$input.json('$')",
"header": "$input.params().header.get($header)",
"headerParam": "$input.params().header.keySet()",
"contentType": "$input.params().header.get('Content-Type')"
}
},