繁体   English   中英

Angular 2,在两个没有直接关系的组件之间共享一个对象

[英]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.

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