[英]What is the difference between using the service variable change in a component versus subscribing to an event from the service?
I have three components. 我有三个组成部分。 recipe, recipe-item and recipe-details.
食谱,食谱项目和食谱细节。 On clicking on a recipe from recipe-item component, recipe details of that particular recipe is displayed (ie recipe-details component is getting activated).
单击配方项目组件中的配方后,将显示该特定配方的配方详细信息(即,配方细节组件已被激活)。
I have one common service - recipe-service. 我有一项共同服务-食谱服务。 Which I am thinking to use it for communicating between all the components.
我正在考虑将其用于所有组件之间的通信。
Approach 1: When I click on a recipe from recipe-item, I will call a function which will point to another function in recipe service which in turn will mark a variable currentRecipe as the clicked recipe passed from recipe-item. 方法1:当我从配方项目单击配方时,我将调用一个函数,该函数将指向配方服务中的另一个函数,该函数将标记一个变量currentRecipe作为从配方项目传递的单击配方。 This currentRecipe value I will access in the recipe/recipe-details components through ngOnInit to display the details.
我将通过ngOnInit在配方/配方详细信息组件中访问此currentRecipe值以显示详细信息。 Will this approach work?
这种方法行得通吗? will the view change as the variable changes in the service?
服务中的变量变化时,视图是否也会变化? I am doubtful of this approach as the ngOnInit only checks while initiating the component.
我对这种方法表示怀疑,因为ngOnInit仅在启动组件时进行检查。
Approach 2: When I click on a recipe from recipe-item, I will call a function which will trigger an event emitter that was declared in the service, but emits currentRecipe directly from the recipe-item component. 方法2:当我从配方项目单击配方时,我将调用一个函数,该函数将触发服务中声明的事件发射器,但直接从配方项目组件中发出currentRecipe。 And, I will subscribe to this event from the ngOnInit of recipe and recipe-detail components to display the details.
并且,我将从配方和配方细节组件的ngOnInit订阅此事件以显示详细信息。
I am a beginner and I am confused between the two approaches. 我是一个初学者,我对这两种方法感到困惑。 I tried the first approach which did not work.
我尝试了第一种无效的方法。 The second approach works.
第二种方法可行。 I am not sure why the first approach did not work.
我不确定为什么第一种方法行不通。 In which scenario I should be using the first approach and in which scenario I should be using the second approach?
在哪种情况下我应该使用第一种方法,在哪种情况下我应该使用第二种方法?
Thank you for the help! 感谢您的帮助!
Both approaches will work, i would suggest you go with the 2nd Approach as both of your component are dependent and have a relationship. 两种方法都行得通,我建议您使用第二种方法,因为您的两个组件都相互依赖并且有关系。
You could use the @input() event emitter to transfer the details to the child component. 您可以使用@input()事件发射器将详细信息传输到子组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.