angular - 无法从 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 领域的新手,欢迎随时提供反馈。
解决方案
这是因为recipes
Angular 更改检测不会捕获更改,因为它在 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
推荐阅读
- azure - 适用于 Java 的 Azure Application Insights 代理导致无法在 JBoss 18 上找到或加载主类 %JAVA_OPTS
- c# - 如何比较 SpecFlow 中的多行参数?
- c# - 在c#中使用/不使用正则表达式清除不需要的十六进制字符
- c++ - 为什么在三元中返回静态大小的数组时 MSVC 2019 会失败?
- javascript - 如何使用 JavaScript 和 Github API 更新托管在 GitHub 存储库中的 JSON 文件
- google-api - API 密钥对谷歌云翻译无效
- sql - Azure SQL 数据库中的 SQL 作业中的语法错误
- python - django中的url可以传入一个空字符串吗?
- javascript - vue-cli-service serve 和 buid 生成不同的样式
- python - 通过 API 向 JIRA 问题添加请求类型