Angular 可观察 returns 订阅者而不是 JSON

Angular Observable returns Subscriber instead of JSON

我有一个功能

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

它 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, …}

现在,我想要的是从包列表中以 JSON 格式获取所选包,但它 returns Subscriber

公司也是如此。

知道如何解决这个问题吗?

您正在获取分配中的订阅,要获取您应该执行类似操作的值。

let selectedPackage;
await this.packages.subscribe(result => {
    result.forEach(element => {
        if (element._id === form.package) {
            selectedPackage = element;
        }
     });
    });

更新

此代码确实有效,但是当您 console.log 值时,您不确定订阅是否已将值设置到变量中,因此您需要将可观察到的值转换为承诺,以便您可以继续使用 async-await 关键字并确保您在 console.log 时间

有值
const p = this.packages.toPromise(); 
let selectedPackage; 
await p.then(result => { 
 result.forEach(element => { 
  if (element._id === form.package) { 
   console.log('debgu'); 
   selectedPackage = element; 
  } 
 }); 
});

在开始使用对象之前,您必须将订阅的结果转换为 json。

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"是一个数组。

希望对您有所帮助!