简体   繁体   English

通过共享单例服务进行Angular2组件通信

[英]Angular2 component communication by shared singleton service

I'm wondering how scopes are defined in angular2 . 我想知道如何在angular2中定义范围。 Currently I have an service OrderService with a property CurrentOrder . 目前我有一个服务OrderService ,其属性为CurrentOrder

I have two components ('order.component', 'clients.component') acting as siblings instantiated by routing. 我有两个组件('order.component', 'clients.component')作为路由实例化的兄弟姐妹。

I provide OrderService in bootstrap and use it in both of my components by 我在bootstrap中提供OrderService并在我的两个组件中使用它

import { OrderService} from './order.service';

and

constructor(private orderService:OrderService){ }

in ClientComponent i set CurrentOrder like orderService.CurrentOrder=someNewOrder . 在ClientComponent中,我将CurrentOrder设置为orderService.CurrentOrder=someNewOrder

after that I'm routing to OrderComponent and try to access orderService.CurrentOrder but its empty. 之后我将路由到OrderComponent并尝试访问orderService.CurrentOrder但它是空的。

shouldn't orderService act as singleton provided in bootstrap ? 不应该orderService作为bootstrap中提供的单例?

如果您希望共享服务只是一个实例,请不要放入组件的providers数组 - 仅在bootstrap调用中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM