Reputation: 1961
I have a function
async submit(form) {
const selectedPackage = await this.packages.toPromise().then(result => {
result.forEach(element => {
if (element._id === form.package) {
return element;
}
});
});
const selectedCompany = await this.companies.toPromise().then(result => {
result.forEach(company => {
if (company._id === form.company) {
return company;
}
});
});
console.log(selectedPackage);
console.log(selectedCompany);
it returns :
Subscriber {closed: false, _parent: null, _parents: null, _subscriptions: Array(1), syncErrorValue: null, …}closed: truedestination: SafeSubscriber {closed: true, _parent: null, _parents: null, _subscriptions: null, syncErrorValue: null, …}isStopped: truesyncErrorThrowable: falsesyncErrorThrown: falsesyncErrorValue: null_parent: null_parents: null_subscriptions: null__proto__: Subscription addCredit-c.ts:76
Subscriber {closed: false, _parent: null, _parents: null, _subscriptions: Array(1), syncErrorValue: null, …}
Now, what I want is to get the selected package as JSON
format from packages list, but it returns Subscriber
The same thing goes for the company.
Any idea how to solve this problem?
Upvotes: 2
Views: 3050
Reputation: 1181
You are getting the subscription in the assignment, to get the value you should do something like.
let selectedPackage;
await this.packages.subscribe(result => {
result.forEach(element => {
if (element._id === form.package) {
selectedPackage = element;
}
});
});
UPDATE
This code actually works but when you console.log the values you are not sure that the subscription has already setted the value into the variable, so you need to convert the observable into a promise so that you can continue using the async-await keywords and be sure that you have the value at the console.log
time
const p = this.packages.toPromise();
let selectedPackage;
await p.then(result => {
result.forEach(element => {
if (element._id === form.package) {
console.log('debgu');
selectedPackage = element;
}
});
});
Upvotes: 2
Reputation: 34
You must convert the result of the suscribe to json before start working with the object.
const selectedPackage = await this.packages.subscribe(result => {
let resultJson= result.json();// or let resultJson= JSON.parse(result);
let elementsSelected= resultJson.filter(element => element._id === form.package);
return elementsSelected;
});
});
"elementsSelected" is an array.
I hope it helps!
Upvotes: 0