2017-09-04 52 views
0

我試圖在我的移動POC(Cordova2/Angular2)中創建購物車功能。 我已經爲組件之間的共享數據創建了服務。我通過組件A添加項並嘗試從組件B讀取。但是,我沒有在組件B中看到這些項。我應該在服務中添加什麼?Angular2在頁面/組件之間共享變量或全局變量

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

成分:

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(); 
    } 
+0

解決的辦法之一是在你的服務,創造一個BehaviorSubject且可觀察到它,然後訂閱它的兩個組成部分。或使用'@ Input' /'@ Output'和EventEmitter來處理您的操作。 – Vic

+0

看看BehaviorSubject - [CLICK](https://www.youtube.com/watch?v=k8hMfoNIo4Y) – Vic

+0

您是否在使用Ionic? – user2085143

回答

1

一切是正確的一件事,你缺少的是提供服務這兩個組件。 您需要在模塊級別共享服務,以表示我的服務在這兩個組件之間共享。

providers: [AppService], 

模塊的整個代碼

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

,如果你想進入更詳細,想知道如何共享兩個模塊之間的數據可以看到share data between tow module

行爲主體 行爲主題是在組件之間共享數據的更好方式,它可以在任何時候處理未來的數據共享ere是一項服務中的數據更改,它會通知其他服務。

在細節看你看這個sharing data between components