首页 > 解决方案 > 无法从 rxjs observable 中提取数据

问题描述

我有一项服务可提供可观察的“食谱”集合

@Injectable({
  providedIn: 'root'
})
export class RecipeService {

  recipes: Recipe[];
  private _recipesSource = new Subject<Recipe[]>();
  recipesMessage$ = this._recipesSource.asObservable();

  constructor() {
    this.recipes = new Array<Recipe>();
    this.recipes.push(new Recipe('Recipe1', 1));
    this.recipes.push(new Recipe('Recipe2', 2));
    this.recipes.push(new Recipe('Recipe3', 3));
    this._recipesSource.next(this.recipes);
  }
}

此外,我有一个角度组件,它为每个配方创建一个垂直的按钮列表RecipeService

@Component({
  selector: 'app-recipe-list',
  template: `
    <div class="btn-group-vertical">
      <button
        *ngFor="let recipe of rs.recipesMessage$ | async"
        type="button" class="btn btn-secondary">
        a
      </button>
   </div>
  `
})
export class RecipeListComponent implements OnInit {

  recipes: Recipe[];
  constructor(private rs: RecipeService) { }

  ngOnInit(): void {
    this.recipes = new Array();
  } 
}

我遇到的问题是提供页面时按钮没有出现。看来我的订阅没有返回任何内容。

附言。如果我的 TypeScript 不是很好,请原谅我。我是 Javascript 领域的新手,欢迎随时提供反馈。

标签: angulartypescriptservicerxjsobservable

解决方案


这是因为recipesAngular 更改检测不会捕获更改,因为它在 aync 订阅调用中发生了变异。

代替

*ngFor="let recipe of recipes"

*ngFor="let recipe of rs.recipesMessage$ | async"

你可以删除

loadRecipes(): void {
    this.rs.recipesMessage$
      .subscribe(
        recipes => this.recipes = recipes
      );
  }

this.loadRecipes()ngOnInit


推荐阅读