【问题标题】:Async function is not working for me it's is showing error异步功能对我不起作用,它显示错误
【发布时间】:2019-09-14 18:20:43
【问题描述】:

**我在显示类别时遇到问题。我正在尝试使用

异步

功能但不显示数据**

<div class="form-group">
    <label for="category">Category</label>
    <select id="category" class="form-control">
      <option value=""></option>
      <option *ngFor="let c of categories$ | async" [value]="c.$key">{{
        c.name
      }}</option>
    </select>
  </div>

我已经尝试过了,但它不起作用

product-form.component.ts

export class ProductFormComponent {
  categories$;

  constructor(categoryService: CategoryService) {
    this.categories$ = categoryService.getCategories();
  }
}

我在这里创建产品数据

save(product) {
    this.productService.create(product);
    console.log(product);
  }

category.service.ts **通过使用

.valueChanges

我能够获取数据,但它没有将数据存储在 firebase db 中。它显示未定义**

export class CategoryService {
  constructor(private db: AngularFireDatabase) {}

  getCategories() {
    return this.db.list('/categories').valueChanges();
  }
}

为了创建产品数据并将其推送到数据库中,我使用了这种方法
product.service.ts

export class ProductService {
  constructor(private db: AngularFireDatabase) {}

  create(product) {
    return this.db.list('/products').push(product);
  }
}

这是我遇到的错误

InvalidPipeArgument: '[object Object]' 用于管道'AsyncPipe'

【问题讨论】:

    标签: html angular typescript


    【解决方案1】:

    列出类别:

    修改getCategories()。添加snapshotChanges()valueChanges()

    试试这样:

    return this.db.list('/categories').snapshotChanges();
    

    或者,

    return this.db.list('/categories').valueChanges();
    

    创建产品:

    $products: FirebaseListObservable&lt;any[]&gt;;

    create(product) {
         return this.$products.push(product);
    }
    

    【讨论】:

    • 谢谢阿德里塔。它正在工作,但通过使用 .valueChanges() 正在显示数据,但即使我们在表单中选择类别后也将数据存储在 db 中。它显示未定义
    • 你还没有分享在数据库中添加类别,我添加了添加产品的代码。 this.$products.push(product)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-25
    • 1970-01-01
    • 1970-01-01
    • 2019-10-14
    • 1970-01-01
    • 2013-11-02
    • 2022-01-11
    相关资源
    最近更新 更多