[英]Angular 2, share an object between two components that have no direct relationship
我有一個像這樣結構的應用程序。
<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
-a中的模板需要此信息。 起初我嘗試使用自定義事件通過@Outuput和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;
}
}
這就是我試圖在component-a中使用它的方法:
ngDoCheck()
{
if(this._sharedService.spec)
{
this.spec= this._sharedService.getSpec();
}
}
問題:
在component-b
設置規范並從component-a
設置ngDoCheck
,檢查是否已設置規范。 它返回為undefined
因此getSpec()
函數不會運行,並且不返回任何規范。 所以我不確定我缺少什么,或者為什么在設置之后我的SharedService
仍然undefined
它。 共享服務是否應該保留對所設置內容的引用? 還是我完全誤解了這個概念?
我還探討了通過promises / 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屬性中的配置。
也許您的服務實際上並未共享。 我的意思是,根據您配置提供程序的方式,您可以有兩個實例。
可以肯定的是,只需在引導應用程序時添加服務:
bootstrap(AppComponent, [ SharedService ]);
請務必刪除兩個組件的providers
屬性中的配置。
如果你對Angular2的分層注入器(這背后的概念)感興趣,你可以看一下這個問題:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.