retrieve 1 variable in array of my controller - arrays

My controller return an array of variables.
return response()->json([$newBauxEnCours, $bienPrixEnBaisse]);
My method for call API Laravel
getProducts(status: string, typeTransac: string): Observable <any> {
let params = new HttpParams();
params = params.append('status', status);
params = params.append('typeTransac', typeTransac);
console.log(params);
if (status !== null && typeTransac !== null) {
// Conversion en nombre
return this.apiClient.get(this.ApiUrl, { params: params});
}else{
console.log('aucune valeur en params')
}
}
ngOnInit(){
this.ArchiveVente$ = this.dataMlsService.getProducts('Vendu', 'Vente');
console.log(this.ArchiveVente$);
}
My problem is : Why retrieve my variable $newBauxEnCours in Angular ?
Thanks

try like this
ngOnInit(){
this.dataMlsService.getProducts('Vendu', 'Vente').subscribe((response: any)=> {
console.log(response);
});
}

GetProducts returns this.apiClient.get() which returns a Observable. The Observable will not get executed until you subscribe to it.
Because the get call is asynchronous you must provide a function (callback) to the subscribe function that will get called when the get is finished.
this.ArchiveVente$ = this.dataMlsService.getProducts('Vendu', 'Vente').subscribe((response: any)=> {
console.log(response);
});
this.ArchiveVente$ is set to the observable. in your html you need to use it with the async pipe. e.g.
<li *ngFor="let varName of ArchiveVente$ | async">
{{ varName.name }}
</li>
you can also just add the data to the variable than you can use is without the async pipe
this.dataMlsService.getProducts('Vendu', 'Vente').subscribe((response: any)=> {
this.ArchiveVente = response;
});
see: https://angular.io/guide/observables for more info

Related

Cannot read property 'emit' of undefined when trying to emit a document

I am trying to create a design for tags of entities in PouchDB with ReactJS. I managed to save my design using the put function, but when I query my design, the response is just an empty array and I am getting following error in console:
TypeError: Cannot read property 'emit' of undefined
I think the problem is in my function that I later use as a map parameter to my design variable:
function emitTagsMap(doc)
{
if (doc !== undefined)
{
if (Array.isArray(doc.tags))
{
doc.tags.forEach(x =>
{
/* Here is probably the problem - this.db is undefined */
this.db.emit(x, null);
});
}
}
};
this.db is declared in constructor:
constructor(service, name)
{
if (!service || !name) throw new Error("PouchDatabase initialized incorrectly");
this.name = name;
this.db = new PouchDB(name);
this.service = service;
this.tagsView();
}
Please bare in mind that I am completely new to PouchDB.
Any ideas how can I initialize the emit function?
Thank you in advance.
I assume, that your function is a part of a JavaScript class (otherwise you have to explain the idea with this). In ES6, you have to bind this to your regular functions. You have two options:
First - bind it via constructor:
constructor() {
this.emitTagsMap = this.emitTagsMap.bind(this);
}
Second - declare the function as an arrow one. This way, react will bind it for you:
emitTagsMap = (doc) =>
{
if (doc !== undefined)
{
if (Array.isArray(doc.tags))
{
doc.tags.forEach(x =>
{
/* Here is probably the problem - this.db is undefined */
this.db.emit(x, null);
});
}
}
};
You don't need to call emit over the database object.
Try this:
function emitTagsMap(doc)
{
if (doc !== undefined)
{
if (Array.isArray(doc.tags))
{
doc.tags.forEach(x =>
{
emit(x, null);
});
}
}
};
According to the PouchDB docs a design document is formed like this:
// first create a new design doc and pass your map function as string into it
var ddoc = {
_id: "_design/my_index",
views: {
by_name: {
map: "function (doc) { if (doc !== undefined) { if (Array.isArray(doc.tags)) { doc.tags.forEach(x => { emit(x, null); }); } } }"
}
}
};
// save it
db.put(ddoc).then(function () {
// success!
}).catch(function (err) {
// some error (maybe a 409, because it already exists?)
});
//Then you actually query it, by using the name you gave the design document when you saved it:
db.query('my_index/by_name').then(function (res) {
// got the query results
}).catch(function (err) {
// some error
});
https://pouchdb.com/guides/queries.html

Vue Old Array Mirroring New Array

I have two arrays declared in my data
data() {
return {
infeed_data:[],
infeed_model:[],
}
},
Once the page is mounted, the following method is kicked off
mounted() {
this.get_rolls_infeed()
},
This method makes a call to my api, then assigns the response to both infeed_data and infeed_model. I then do a for loop and create new key/values on the infeed_model, however the new key/values show up in the infeed_data.
get_rolls_infeed(){
var vthis = this;
axios.post(myapiurl)
.then(function(response){
vthis.infeed_data = response.data[0]
vthis.infeed_model = response.data[0]
vthis.infeed_model.forEach(function(record, index){
vthis.infeed_model[index].usage_type = 0
})
})
},
My Vue html
<b>Infeed Data</b>
<p>{{infeed_data}}</p>
<br />
<b>Infeed Model</p>
<p>{{infeed_model}}</p>
Rendered html to show how _data is mirroring _model
Can you try to do this instead of your code?
vthis.infeed_data = response.data[0];
vthis.infeed_model = response.data[0].slice();

An empty array is returned when calling $http.get it within a service [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I want to get the name from an array that is being generated from $http.get, however this is returning an empty array. When i do a console it see the array populated however when i loop inside the array to get the value of name property based on whether an id is equal to a certain, the array is empty.
In my controller i have a service call that shall return the name value.
var params = { Id: $scope.Id, SettingId: $scope.SettingId };
$scope.selectedUserName = helloService.getSelectedUserName($scope.UserId, params);
In my service
I have used the getUserList function to populate the list of user in a dropdown and it works by generating the array with the values.
However When i got another page , i want to be able to display the name of the selected user, so I wanted to use the same getUserList function to retrieve the name
this.getUserList = function (val) {
var usersObj = [];
var url = "/api/v1/hello/getusers";
var params = { Id: val.Id, SettingId: val.SettingId };
var config = { params: params };
var promise = $http.get(url, config)
.then(function (response) {
angular.forEach(response.data, function (key, value) {
angular.forEach(key, function (k, index) {
usersObj[index] = ({ userId: k.userId, name: k.name});
});
});
},
function errorCallback(response) {
console.log("Unable to perform get request");
throw response;
});
var usersList = usersObj;
return usersObj;
};
this.getSelectedUserName = function (id, param) {
var name = "";
var userList =this.getUserList(param);
angular.forEach(userList, function (value, key) {
if (value.userId == id)
name = value.name;
});
return name;
}
Array length is 0 but if i do a console.log(userList) before the loop , the array display the list of user data
this.getSelectedUserName = function (id, param) {
var name = "";
var userList =this.getUserList(param);
console.log(userList) ;
angular.forEach(userList, function (value, key) {
if (value.userId == id)
name = value.name;
});
return name;
}
Thank you for kind responses.
Please see screenshot
This is simple Javascript, not specific to Angular. You can do
userList.forEach(user => {
if(user.userId === id) {
name = user.name;
}
});
return name;
you can try like this.
here we are using a async await.
Service
this.getUserList = function (val) {
var usersObj = [];
var url = "/api/v1/hello/getusers";
var params = { Id: val.Id, SettingId: val.SettingId };
var config = { params: params };
return new Promise((resolve, reject) => {
$http.get(url, config)
.then(function (response) {
angular.forEach(response.data, function (key, value) {
angular.forEach(key, function (k, index) {
usersObj[index] = ({ userId: k.userId, name: k.name});
});
});
},
function errorCallback(response) {
console.log("Unable to perform get request");
throw response;
});
var usersList = usersObj;
resolve(usersObj);
});
};
this.getSelectedUserName = async function (id, param) {
var name = "";
var userList = await this.getUserList(param);
console.log(userList);
angular.forEach(userList, function (value, key) {
if (value.userId == id)
name = value.name;
});
return name;
}
let me know if it is working or not.
EDIT:
If you're only trying to match one id in the array of users you don't even need to loop:
anArray = source.filter(source => source.toLowerCase().indexOf(id) === 0);
or
anObject = source.find(obj => obj.id === id);
Which Angular version is this? Your tag denotes 2.+ but you have $scope there which is ng1.x
Why can't you use ngFor in your view since you already have your arrays. You don't need to sort them in the control.
component
this.getSelectedUserName = function (id, param) {
let name = ""; // should be array if you want to add unames to it
let userList = this.getUserList(param);
// what is `angular` here? And why loop here? Use ngFor in view.
angular.forEach(userList, function (value, key) {
if (value.userId == id){
name = value.name; // will be overwritten each time
// should be name.push(value.name); // but loop in view instead
}
});
// this.users = name; // for your original sorted version
this.users = userList;
}
In your view
<li *ngFor="let user of users; index as i;>
{{user.name}}
</li>

How to return response to calling function in AngularJS?

I am calling this method testDataService, which is defined in the same JS file. This method returns a list which it gets from an API call. I want to set that value to model and return model object. but my return function is getting called before my API returns the response. How can i make sure return function will get called only after the above if block get the data from API.
getTestData(model) {
model.name = "practice";
model.value = 2;
// this if loop is calling an API and setting up data into model.
if(this.model.form.length>0 && this.model.form[0].entityName === 'test'){
let responseList;
this.testDataService(this.model).then(response => {
responseList = response;
model.class = responseList;
});
}
return this.model;
// this return function is getting called before the api returns its data. How can i make sure this return will get called only after the above if block get the data from API.
}
This is method definition
testDataService(model) {
let profileType = "test";
let profileId = "test_profile";
let configCategory = "test";
return this.referenceDataService.getTestData(profileType, profileId, configCategory);
}
You need to pass return statement from the callback, instead of placing it outside.
getTestData(model) {
model.name = "practice";
model.value = 2;
// this if loop is calling an API and setting up data into model.
if (this.model.form.length > 0 && this.model.form[0].entityName === 'test') {
this.testDataService(this.model).then(response => {
let responseList = response;
model.class = responseList;
return this.model;
}).then(response => {
return null;
});
}
}
testDataService(model) {
let profileType = "test";
let profileId = "test_profile";
let configCategory = "test";
return this.referenceDataService.getTestData(profileType, profileId, configCategory);
}

AngularJS: promise in a loop

I am unable to do the promise looping.
I make a service call to get list of providers, then for each provider, I make another service call to get a customer.
A provider has 1 or more customers. So eventual list of customer is to be decorated and displayed.
In other format I am trying to achieve:
*serviceA.getProvider(){
foreach(providers){
foreach(provider.customerID){
serviceB.getCustomer(customerId)
}
}
}
.then(
foreach(Customer){
updateTheCustomer;
addUpdatedCustomerToAList
}
displayUpdatedCustomreList();
)*
I have written following code, that isn't working
doTheJob(model: Object) {
let A = [];
let B = [];
let fetchP = function(obj) {
obj.Service1.fetchAllP().then(function (response) {
let P = cloneDeep(response.data);
_.forEach(P, function(prov) {
_.forEach(prov.CIds, function(Id) {
A.push(Id);
});
});
_.forEach(A, function(CId) {
return obj.Service2.getById(CId);//what works is if this statement was: return obj.Service2.getById(A[0]);
//So, clearly, returning promise inside loop isn't working
});
})
.then(function(response) {
B.push(response.data); //This response is undefined
angular.forEach(B, function (value) {
obj.updateAdr(value)
});
obj.dispay(B);
});
};
fetchP(this);
}
forEach don't stop when you use return inside of it, try to use a plain loop instead, why you don't just loop with for ?
_.forEach(A, function(CId) {
return obj.Service2.getById(CId);
}
as stated by #Ze Rubeus if you return inside a callback within a for loop that value will be lost, since it's not returned to the caller.
probably you wanted something like this
return Promise.all(A.map(function(CId){
//collect each promise inside an array that will then be resolved
return obj.Service2.getById(CId);
})

Resources