页面/组件之间的Angular2共享变量或全局变量 [英] Angular2 Sharing variable or Global variable between pages/Components

查看:191
本文介绍了页面/组件之间的Angular2共享变量或全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在MOBILE POC(Cordova2 / Angular2)中创建购物车功能。
我已经创建了用于组件之间共享数据的服务。我通过组件A添加了项并尝试从组件B中读取。但是我没有在组件B中看到那些项。我应该在服务中添加什么?

I'm trying to create Cart functionality in my MOBILE POC (Cordova2/Angular2). I've created Service for share data between components. I'adding items through Component A and trying to read from Component B. But I'm not seeing those items in Component B. What should I add in Service?

import { Injectable  } from '@angular/core';    
@Injectable()    
export class CartService {
    private vijayCart: Array<any> = [];
    GetCart() {
        return this.vijayCart;
    }
    SetCart(item) {
        this.vijayCart.push(item);
    }
}  

组件A:

addItemToCart(item) {
    this.cartService.SetCart(item);
    //this.cartService.vijayCart.push(item);
    this.cartLenth = this.cartService.GetCart().length;
}

组件B:

  ngOnInit(): void {
      this.cartSer = this.cartService.GetCart();
  }


推荐答案

一切都是正确的一件事缺少的是为这两个组件提供服务。
,您需要在模块级别共享服务,以说我的服务在这两个组件之间共享。

Everything is correct one thing you are missing is to provide the service to both the components. you need to share the service at module level to say that my service is shared between these two components.

 providers: [AppService],

模块的整个代码

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [AppService],
  bootstrap: [AppComponent]
})
export class AppModule { }

如果您想了解更多细节并想知道如何在两个模块之间共享数据,可以看到在两个模块之间共享数据

if you want to go into more detail and want to know how to share data between two modules you can see share data between tow module

行为主题
行为主题是在组件之间共享数据的更好方法,并且一旦发生数据更改,它就可以处理将来的数据共享合而为一服务,它会通知其他服务。

Behaviour subject Behaviour subject is a better way to share data between components and it handles future data sharing when ever there is a data change in one service, it notifies the other service.

要查看详细信息,您可以查看此在组件之间共享数据

to see in details you can see this sharing data between components

这篇关于页面/组件之间的Angular2共享变量或全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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