So basically I'm trying to achieve a reports card and I'm making a data query per each subject the student have. Unfortunately all the fields are getting replaced instead of leaving the previous one as it is. I may think this is some sort of Ionic limitation, so please would love insight in what I'm doing wrong and how to achieve what I'm trying to do.
Provider:
tipos(data) {
return new Promise((resolve, reject) => {
let headers = new HttpHeaders();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let params: HttpParams = this.serialize(data);
this.http.post('https://xyz.ec/app/app/tipos', params, { headers: headers })
.subscribe(res => {
//console.log(res);
resolve(JSON.parse(JSON.stringify(res)));
}, (err) => {
reject(err);
});
});
}
actividades_det(data) {
return new Promise((resolve, reject) => {
let headers = new HttpHeaders();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let params: HttpParams = this.serialize(data);
this.http.post('https://xyz.ec/app/app/actividades-detalle', params, { headers: headers })
.subscribe(res => {
//console.log(res);
resolve(JSON.parse(JSON.stringify(res)));
}, (err) => {
reject(err);
});
});
}
TS File:
export class NotasIndPage {
data: any = { uid: '' };
mdata: any = {uid:'',idm: '' };
pdata: any = {idpa:'' };
matdata: any = { uid:'',idm: '',idp:'' };
tipdata: any = { uid:'',idm: '',idpe:'',idpa:'',idt:'' };
tipos: any =[];
items: any =[];
mat: any =[];
par: any =[];
submitted = false;
toast: any;
uid: any;
id: any;
idpe: any;
idpa: any;
mnombre: any;
pnombre: any;
constructor(
public userData: UserData,
public router: Router,
public toastController: ToastController,
private storage: Storage,
public route: ActivatedRoute) {
}
ionViewWillEnter() {
this.storage.get('sess').then((val) => {
if(val){
this.data.uid=val;
this.uid=val;
this.route.params.subscribe(params => {
this.id = params['idm'];
this.idpe = params['idpe'];
this.idpa = params['idpa'];
});
this.matdata.idm=this.id;
this.mdata.idm=this.id;
this.mdata.uid=this.uid;
this.pdata.idpa=this.idpa;
this.userData.parcial(this.pdata).then(datpa => {this.par = datpa; this.pnombre=this.par[0].nombre;});
this.userData.materia(this.mdata).then(datma => {this.mat = datma; this.mnombre=this.mat[0].nombre;});
//Bloque de carga de datos en formulario
this.userData.tipos(this.data)
.then(dat => {
this.tipos = dat;
for(let i=0;i<this.tipos.length;i++){
this.tipdata.uid=this.uid;
this.tipdata.idm=this.id;
this.tipdata.idpe=this.idpe;
this.tipdata.idpa=this.idpa;
this.tipdata.idt=dat[i].id_tipo;
console.log(this.uid+" - "+this.id+" - "+this.idpe+" - "+this.idpa+" - "+dat[i].id_tipo);
this.userData.actividades_det(this.tipdata).then(datt => {this.items = datt; console.log(datt);});
}
});
//Fin de bloque de carga de datos
}else{
this.router.navigateByUrl('/login');
}
});
}
HTML file:
<ion-card *ngFor="let tipo of tipos" >
<ion-card-header>
<ion-card-subtitle>Id: {{tipo.id_tipo}} </ion-card-subtitle>
<ion-card-title>{{tipo.nombre}}</ion-card-title>
</ion-card-header>
<ion-card-content>
<ng-container *ngFor="let item of items" ><ion-label class="under" *ngIf="item.id_actividad!=0" > {{item.nombre}} - {{item.nota}} : {{item.descripcion}}<br></ion-label></ng-container>
</ion-card-content>
</ion-card>
Image of how the the report card is designed
The problem is when you update this.items. You are in a for-loop, so each value will erase last value. A solution could be to add a property to tipos this way:
this.userData.tipos(this.data)
.then(dat => {
this.tipos = dat;
for(let i=0;i<this.tipos.length;i++){
// ...
this.userData.actividades_det(this.tipdata).then(datt => {this.tipos[i].items = datt; console.log(datt);});
}
});
and then use it in html:
<ng-container *ngFor="let item of tipo.items" ><ion-label class="under" *ngIf="item.id_actividad!=0" > {{item.nombre}} - {{item.nota}} : {{item.descripcion}}<br></ion-label></ng-container>
Related
i want to iterate over an array, however my array is an observer. i have tried several ways, like converting to an array. nothing works.
does anyone have a suggested solution?
i'm pretty stuck on this.
here is my code:
var vm = new Vue({
el: '#app',
data() {
return {
segmenteConfig: []
}
},
methods: {
async loadData(type) {
var url = null;
console.log("used configs -> ", this.segmenteConfig);
this.segmenteConfig.forEach(segmenteConfig => {
if (segmenteConfig.type === type) {
url = segmenteConfig.url;
console.log("used configs url -> ", url);
}
})
}
loadConfig() {
var config = [];
axios.get("ressources/segmente.json")
.then(response => {
response.data.Segmente.forEach(segmentConfig => {
this.segmenteConfig.push(segmentConfig);
});
});
}
},
created() {
this.loadConfig();
this.loadData('internet');
}
});
I'm trying to upload a multipart form in nativescript and I'm using http-background. I keep getting the error Class constructor Observable cannot be invoked without 'new'. I've tried changing the compilerOptions target to es5 and es2017, but nothing changed.
Here's all my code from the component.
onSave(){
console.log("clicked")
this.proccessImageUpload(this.file);
}
public onSelectSingleTap() {
this.isSingleMode = true;
let context = imagepicker.create({
mode: "single"
});
this.startSelection(context);
}
private startSelection(context) {
let that = this;
context
.authorize()
.then(() => {
that.imageAssets = [];
that.imageSrc = null;
return context.present();
})
.then((selection) => {
console.log("Selection done: " + JSON.stringify(selection));
this.file = selection[0]._android;
that.imageSrc = that.isSingleMode && selection.length > 0 ? selection[0] : null;
// set the images to be loaded from the assets with optimal sizes (optimize memory usage)
selection.forEach(function (element) {
element.options.width = that.isSingleMode ? that.previewSize : that.thumbSize;
element.options.height = that.isSingleMode ? that.previewSize : that.thumbSize;
});
that.imageAssets = selection;
}).catch(function (e) {
console.log(e);
});
}
// proccess image function
proccessImageUpload(fileUri) {
var backgroundHttp = require("nativescript-background-http");
return new Promise((resolve, reject) => {
// body...
var request = {
url: 'http://192.168.0.2:4000/api/posts',
method: "POST",
headers: {
"Content-Type": "application/octet-stream",
"user_id": "<user_id>"
},
description: 'Uploading profile image..',
androidAutoDeleteAfterUpload: false,
androidNotificationTitle: 'Profile image'
}
var params = [
{ name: "title", value: "test" },
{ name: "content", value: "test" },
{ name: "fileToUpload", filename: fileUri, mimeType: "image/jpeg" }
];
var backgroundSession = backgroundHttp.session('image-upload');
var task = backgroundSession.uploadFile(fileUri, request);
task.on("progress", (e) => {
// console log data
console.log(`uploading... ${e.currentBytes} / ${e.totalBytes}`);
});
task.on("error", (e) => {
// console log data
console.log(`Error processing upload ${e.responseCode} code.`);
reject(`Error uploading image!`);
});
task.on("responded", (e) => {
// console log data
console.log(`received ${e.responseCode} code. Server sent: ${e.data}`);
// var uploaded_response = JSON.parse(e.data);
});
task.on("complete", (e) => {
// console log data
console.log(`upload complete!`);
console.log(`received ${e.responseCode} code`);
// console.log(e.data);
})
resolve(task);
});
}
I know the issue is coming from this line.
var task = backgroundSession.uploadFile(fileUri, request);
Any help would be greatly appreciated!
You use old version if nativescript-background-http plugin
You have to install latest version
tns plugin add #nativescript/background-http
I was able to get this working by installing tns version 6.
I had exactly the same problem. I got this from slack.com, compliments Chris Vietor
"tns plugin add nativescript-background-http" works with nativescript 6.
"tns plugin add #nativescript/background-http" works with nativescript 7.
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);
I have an application built using the MEAN Stack, I am able to display one record at a time when using this method:
in my member model I have:
module.exports.getMemberByRFID = function(rfidkey, callback){
const query = {rfidkey: rfidkey}
Member.findOne(query, callback);
}
In my routes file I have:
// Authenticate Member
router.post('/authenticatemember', (req, res, next) => {
const rfidkey = req.body.rfidkey;
Member.getMemberByRFID(rfidkey, (err, member) => {
if(err) throw err;
if(member){
const token = jwt.sign(member, config.secret, {
expiresIn: 50 //1 week
});
res.json({
success: true,
token: 'JWT2 '+token,
member: {
id: member._id,
firstname: member.firstname,
surname: member.surname,
email: member.email,
expirydate: member.expirydate
}
});
} else {
return res.json({success: false, msg: 'member not found'});
}
})
});
In my AuthService.ts file I have:
authenticateMember(member){
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.post('http://localhost:3000/users/authenticatemember', member,{headers: headers})
.map(res => res.json());
}
And then in my angular TS file upfront I have:
onSearchSubmit(){
var inputElement = <HTMLInputElement>document.getElementById('rfidkey');
const member = {
rfidkey: inputElement.value
}
this.authService.authenticateMember(member).subscribe(data => {
if(data.success){
this.authService.storeMemberData(data.token, data.member)
console.log(data.member);
var newexpiry = new Date(data.member.expirydate);
var today = new Date();
if (today > newexpiry) {
this.flashMessage.show('member has expired', {
cssClass: 'alert-danger',
timeout: 5000});
} else {
this.flashMessage.show('member is active', {
cssClass: 'alert-success',
timeout: 5000});
}
var n = newexpiry.toString();
var inputElement = <HTMLInputElement>document.getElementById('firstname');
inputElement.value = data.member.firstname;
var inputElement = <HTMLInputElement>document.getElementById('surname');
inputElement.value = data.member.surname;
var inputElement = <HTMLInputElement>document.getElementById('email');
inputElement.value = data.member.email;
var inputElement = <HTMLInputElement>document.getElementById('expirydate');
inputElement.value = n;
// this.router.navigate(['searchmember']);
} else {
this.flashMessage.show(data.msg, {
cssClass: 'alert-danger',
timeout: 5000});
var inputElement = <HTMLInputElement>document.getElementById('firstname');
inputElement.value = "";
var inputElement = <HTMLInputElement>document.getElementById('surname');
inputElement.value = "";
var inputElement = <HTMLInputElement>document.getElementById('email');
inputElement.value = "";
var inputElement =
<HTMLInputElement>document.getElementById('expirydate');
inputElement.value = "";
this.router.navigate(['/searchmember']);
}
});
}
This gives me the following result:
Searching for a single record
Now what I want to do is have a page named Display All Members, and display all records in a datatable which can be searched and sorted.
Does anyone know how I can find ALL records with mongoose and send the list of all members to the front end Angular 2 application and place them in to the table?
thanks!
My code has this HTML snippet:
<div ng-repeat="wf in wos.word.wordForms">
{{ wf }}
<textarea ng-change="wf.statusId = 2"
ng-model="wf.definition">
</textarea>
...
In a service I have this:
wordFormCheckAndUpdate = (): ng.IPromise<any> => {
var self = this;
var promises = [];
angular.forEach(self.word.wordForms, function (wf, key) {
if (wf.statusId == Status.Dirty) {
if (wf.createdDate) {
var updatePromise = self.wordFormUpdateSubmit(wf);
promises.push(updatePromise);
} else {
var addPromise = self.wordFormAddSubmit(wf);
promises.push(addPromise);
}
}
});
return self.$q.all(promises);
};
wordFormAddSubmit and wordFormUpdateSubmit modify the data in wf:
wf = angular.copy(response.data);
wf.statusId = 3;
wf.abc = "test"
When one of these functions is called it does not seem to change what is displayed above the textarea and the statusId still shows as 2 and "test" does not appear. Does anyone have any ideas what might be happening?
Update. Here are the two functions that are called:
wordFormAddSubmit = (wf: IWordForm): ng.IPromise<any> => {
var self = this;
return self.$http({
url: self.ac.dataServer + "/api/WordForm/Post",
method: "POST",
data: wf
})
.then(
(response: ng.IHttpPromiseCallbackArg<IWordForm>): any => {
wf = angular.copy(response.data);
self.$timeout(function () {
wf.statusId = 3;
wf.sourceId = 999;
}, 3);
},
(error: ng.IHttpPromiseCallbackArg<any>): any => {
self.ers.error(error);
return self.$q.reject(error);
});
}
wordFormUpdateSubmit = (wf: IWordForm): ng.IPromise<any> => {
var self = this;
return self.$http({
url: self.ac.dataServer + "/api/WordForm/Put",
method: "PUT",
data: wf
})
.then(
(response: ng.IHttpPromiseCallbackArg<IWordForm>): any => {
wf = angular.copy(response.data);
//$timeout(function () {
wf.statusId = 3;
//}, 1);
var a = wf;
var b = wf;
},
(error: ng.IHttpPromiseCallbackArg<any>): any => {
self.ers.error(error);
return self.$q.reject(error);
});
}