簡體   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