【发布时间】:2026-01-24 23:20:03
【问题描述】:
我对 Angular 2+ 非常陌生(大约一周),我对可观察部分有疑问。
我有这个服务:
export class GetProductsService {
allProducts;
constructor(private http: HttpClient) {
this.http.get('https://jsonplaceholder.typicode.com/posts').subscribe({
next: data => this.allProducts = data,
error: err => console.log(err)
});
}
getAllProducts() {
return this.allProducts;
}
在构造函数中,我发出一个获取请求以检索一些假“产品”。
我检索到的产品,我存储在一个属性中,以便将来我可以更轻松地使用该属性上的其他功能。
现在这是我的问题:我有这个组件
export class AllProductsComponent implements OnInit {
allProducts: any;
constructor(private http: HttpClient, private productsService: GetProductsService) {}
ngOnInit(): void {
this.allProducts = this.productsService.getAllProducts();
}
}
从 ProductService OnInit 中检索 products 属性,但是考虑到它是一个 observable,当其他组件尝试检索 allProducts 属性时,它还没有从 observable 流中完全加载。
如何解决这个问题,我可以看到这是一个常见的问题,这就是为什么我还要求对这个主题有更多的总体更好的理解。我了解它是异步的,我了解它是什么。
我的尝试:
我尝试让服务返回 Observable 而不是设置自己的状态,但是当我实现一个函数来检索特定产品时,我必须再次进行 HTTP 调用,而不是使用内部状态。
非常感谢您的宝贵时间!
【问题讨论】:
-
您能告诉我们您在哪里导入服务吗?如果服务是@Injectable (providedIn: Root),则必须确保在组件中使用服务之前注入服务,而不是与上面的代码同时注入。
-
是的,它提供在:根目录中。我如何确保在其他组件调用它之前注入它? @Lievno
标签: angular rxjs angular2-observables