2016-04-29 74 views
3

我有一個像這樣構建的應用程序。Angular 2,在沒有直接關係的兩個組件之間共享對象

<app> 
    <header> 
     <component-a></component-a> 
    </header> 
    <div> 
    <router-outlet></router-outlet> 
    <component-b></component-b> <!-- loaded through router --> 
    </div> 
</app> 

component-b一些數據被檢索,後來設置爲一個新的對象。例如,像這樣的東西..

{ 
    infoThatComponentANeeds : true, 
    someMoreInfoAddedFromCompB : [] 
} 

此模板需要component-a的信息。起初我試圖通過@Outuput and eventEmitter使用自定義事件將信息傳遞給component-a。但我無法讓它冒出來。我懷疑這與它通過路由器加載有關。所以現在我試圖使用共享服務來共享這兩個組件之間的數據。

我的服務至今:

import {Injectable} from 'angular2/core'; 

@Injectable() 
export class SharedService 
{ 
    public spec:Spec= null; 

    public getSpec() 
    { 
     return this.spec; 
    } 
    public setSpec(spec:Spec) 
    { 
     this.spec = spec; 
    } 
} 

這是我正在嘗試在組件的一個使用它:

ngDoCheck() 
{ 
    if(this._sharedService.spec) 
    { 
     this.spec= this._sharedService.getSpec(); 
    } 
} 

問題:

規格設定在component-b和之後從component-a檢查以查看是否已設置規範。它返回爲undefined,所以getSpec()函數不運行,並且不返回規範。所以我不確定我錯過了什麼,或者爲什麼在SharedService設置後它仍然是undefined。共享服務是否應該參照設定的內容?或者我完全誤解了這個概念?

我也探索過通過promise/observables共享這些數據的方法。不過,我還沒有任何運氣。而且我發現的大多數例子都使用了HTTP,在這一點上我真的不需要這些。

更新:

下面是更多的一些信息。

Boot.ts

import {bootstrap} from 'angular2/platform/browser'; 
import {HTTP_PROVIDERS} from 'angular2/http'; 
import { 
    ROUTER_PROVIDERS, 
    APP_BASE_HREF, 
    Location, 
    LocationStrategy, 
    HashLocationStrategy, 
    PathLocationStrategy 
} from 'angular2/router'; 

import {AppComponent} from './components/app.component'; 
import {SharedService} from './services/shared.service'; 

bootstrap(<any>AppComponent, [ 
    ROUTER_PROVIDERS, 
    SharedService, 
    provide(LocationStrategy, {useClass: PathLocationStrategy}) 
]); 

AppComponent.ts

import {AfterViewInit, Component, OnInit} from 'angular2/core'; 
import {RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router'; 
import {ComponentA} from './componentA'; 


@Component({ 
    selector : 'body', 
    directives : [ComponentA, ROUTER_DIRECTIVES], 
    template : ` 
     <app> 
      <header> 
       <component-a></component-a> 
      </header> 
      <div> 
       <router-outlet></router-outlet> 
      </div> 
     </app> 
    ` 
}) 

@RouteConfig([ 
    {path: '/:appName/', name: 'ComponentB', component: ComponentB} 
]) 

export class AppComponent 
{ 
    constructor(){} 
} 

更新2:

這裏是我創建的嘗試隔離問題上plunker。我刪除了路由器的東西,並簡化了整個事情。我仍然看到同樣的結果..

https://plnkr.co/edit/kx6FWWGS1i04bH5J9DXM?p=preview

觀看console.log()

修正:

這是關鍵。

務必刪除 兩個組件的providers屬性中的配置。

回答

1

也許你的服務並沒有實際共享。我的意思是根據配置提供者的方式,你可以有兩個實例。

可以肯定的,只是這樣引導您的應用程序時添加的服務:

bootstrap(AppComponent, [ SharedService ]); 

一定要刪除你的兩個組件的providers屬性配置。

如果你有興趣Angular2(這背後的概念)的分層噴射器,你可以看一下這個問題:

+0

謝謝您的答覆。我其實也嘗試過。仍然沒有運氣。儘管可以確定,但我會再次嘗試。 –

+0

你可以添加組件的配置嗎?而你推動你的應用程序的方式......謝謝! –

+0

另一件事是可以肯定,當你更新/根據你利用的鉤子方法獲得價值(ngOnInit,ngDoCheck,...) –

相關問題