Angular Observable返回订阅者而不是JSON

时间:2017-11-06 10:15:25

标签: angular observable subscriber

我有一个功能

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

它返回:

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格式,但它返回Subscriber

同样的事情发生在公司。

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

2 个答案:

答案 0 :(得分:1)

您正在获取作业中的订阅,以获得您应该做的事情。

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

更新

这段代码实际上有效,但是当你在console.log中输入值时,你不确定订阅是否已经将值设置到变量中,因此你需要将observable转换为promise,以便你可以继续使用async-等待关键字并确保您具有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; 
  } 
 }); 
});

答案 1 :(得分:0)

在开始使用对象之前,必须将suscribe的结果转换为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"是一个数组。

我希望它有所帮助!

相关问题