Search code examples
angularobservablesubscriber

Angular Observable returns Subscriber instead of JSON


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?


Solution

  • 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; 
      } 
     }); 
    });