Angular-解析器和组件不共享注入的服务? [英] Angular - resolver and component not sharing injected service?

查看:55
本文介绍了Angular-解析器和组件不共享注入的服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的产品列表组件中有一个表来显示某些产品.数据量适中,因此我添加了一个解析器,直到加载数据后才将用户降落在页面上.现在,我的解析器注入了我的产品服务,该产品具有自己的方法来从后端加载数据并将产品保存在服务内部的数组中.因此,我的解析器将注入此服务,调用加载产品函数以预取数据,然后加载组件.

I have a table to display some products in my products list component. There is a moderate amount of data, so I've added in a resolver to not land the user on the page until the data is loaded. Right now, my resolver injects my products service, which has its own methods to load the data from my backend and save the products in an array inside the service. So my resolver injects this service, calls the load products function to prefetch the data and then the component loads.

现在的问题是,重用产品列表组件中数据的最佳方法是什么?出于某种原因,如果我将相同的服务注入到产品列表组件中,则可以看到未加载产品,因此我不确定我的解析器和组件是否将相同的服务注入到我的单例中.

The question is now, what's the best way to re-use the data in the products list component? For some reason, if I inject the same service into the products list component, I can see that the products are not loaded, so I'm not sure if my resolver and component are injecting the same singleton of my service.

如果我仅使用解析器传递从服务本身获得的产品,则我的组件可以访问这些产品,但是当涉及到对它们进行更新时,它不会在对我的产品进行更改产品列表服务,其他组件在其他位置也需要.

If I simply use the resolver to pass along the products that it got from the service itself, then my component can get access to these, but when it comes to making updates to them, it won't be writing changes to my products list service, which is needed elsewhere for other components.

这种设置的最佳结构/方法是什么?我敢肯定这不会罕见吗?

What's the best structure/approach to this kind of setup. I'm sure it can't be that uncommon?

推荐答案

如果您查看Angular文档,则表示如下:请勿在共享模块中指定应用程序范围内的单例提供程序.导入共享模块的延迟加载的NgModule制作了服务的自己的副本."

If you look at Angular documentation there is stated as follows "Do not specify app-wide singleton providers in a shared module. A lazy-loaded NgModule that imports that shared module makes its own copy of the service.."

因此,您应该在核心模块中提供您希望拥有的一项服务,该模块在应用程序启动时将其导入一次,而永远不会在其他任何地方导入.

So an service you want to have as an singleton should be provided in the Core module which you import once when the app starts and never import anywhere else.

此处是指向核心模块的详细说明的链接.

祝你有美好的一天:)

这篇关于Angular-解析器和组件不共享注入的服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆