繁体   English   中英

如何在Angular中返回一个observable?

[英]How to return an observable in Angular?

我正在按照教程填写选择列表。

老师正在使用Angular4,我正在使用最新版本,所以我认为API已经改变了。

我试图在名为CategoryService的类中使用此方法:

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

在我的构造函数中另一个名为ProductFormComponent的类中,我试图返回一个可以在HTML中捕获的observable

categories$;

constructor (
    private router: Router,
    private categoryService: CategoryService,
    private productService: ProductService) {
    this.categories$ = categoryService.getCategories();
}

我的HTML看起来像这样:

<div class="form-group">
    <label for="category">Category</label>
    <select #category="ngModel" ngModel name="category" id="category" class="form-control" required>
        <option value=""></option>
        <option *ngFor="let c of categories$ | async" [value]="c.$key">
            {{ c.name }}
        </option>
    </select>
    <div class="alert alert-danger" *ngIf="category.touched && category.invalid">
        Category is required.
    </div>
</div>        

这给出了错误

错误:InvalidPipeArgument:管道'AsyncPipe'的'[object Object]'

什么是我做错了什么会解决这个问题?

如果this.db.list()未返回Observable ,则可以使用以下命令:

import { of } from 'rxjs';

class CategoryService {

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

}

这会将您的数据包装在一个可观察的数据中。

但是如果操作是完全同步的,那么就没有理由使用Observable。

看起来下面的方法没有返回一个可观察的 -

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

我想“this.db.list('/ categories');” 返回一个简单的数组。 为了确保getCategories()返回一个observable,请执行以下操作 -

getCategories() {
  const values = this.db.list('/categories');
  return of(values);
}

“of”是一个rxjs运算符。 从“rxjs”导入它。 请注意我假设this.db.list('/ categories'); 正在返回简单的数组。 理想情况下,您使用HTTP客户端来调用后端,后端返回包含在observable中的数据。

我相信您的问题是您正在使用旧版本的firebase连接器的旧教程。

在版本5上有一些必要的更改。

在您的服务中,您需要做这样的事情

getCategories() {return this.db.list('/categories')
.snapshotChanges()
.pipe(
    map(categories => categories.map(category => ( { key: category.key, ...category.payload.val() } )))
        );}

如果您希望以后能够使用key (您还应该在对象中定义)

如果您不需要,可以在服务中使用以下选项:

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

这些选项是firebase API 5.0上用于返回可观察对象的新格式。 它不再像以前一样在4.0版本上返回

有关此更多详细信息以及更适合您的版本,请查看有关更改的文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM