7

我在我的主要组件中发出一个事件:

主要组件.ts

this.sharedService.cartData.emit(this.data);

这是我的 sharedService.ts

import { Component, Injectable, EventEmitter } from '@angular/core';
export class SharedService {
    cartData = new EventEmitter<any>();
} 

在我的另一个(子)组件中,我想访问这个值,但不知何故,订阅不起作用:

仪表板.ts

private myData: any;

constructor(private sharedService: SharedService) {
    this.sharedService.cartData.subscribe(
        (data: any) => myData = data,
        error => this.errorGettingData = <any>error,
        () => this.aggregateData(this.myData));
}

我错过了什么吗?当我将数据作为 Injectable 传递时,它工作正常。发出事件(在主组件中)发生在一些 REST 调用之后。

更新

所以问题是子组件是在事件第一次发出之后创建的。我想在这种情况下最好将数据直接注入subcompnent

4

2 回答 2

9

更新: 不再维护 Plunker 示例请在此处使用 StackBlitz 示例 https://stackblitz.com/edit/stackoverflow-questions-45351598-angular?file=src%2Fapp%2Fapp.component.ts

我使用您上面提供的代码创建了一个有效的 plunker 示例。https://plnkr.co/edit/LS1uqB?p=preview

import { Component, NgModule, Injectable, EventEmitter, AfterViewInit } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';


@Injectable()
export class SharedService {
    cartData = new EventEmitter<any>();
} 

@Component({
  selector: 'app-app',
  template: `
    <h1>
      Main Component <button (click)="onEvent()">onEvent</button>
    </h1>
    <p>
      <app-dashboard></app-dashboard>
    </p>
  `,
})
export class App implements AfterViewInit {
  data: any = "Shared Data";

  constructor(private sharedService: SharedService) {
  }

  ngAfterViewInit() {
    this.sharedService.cartData.emit("ngAfterViewInit: " + this.data);
  }

  onEvent() {
    this.sharedService.cartData.emit("onEvent: " + this.data);
  }
}

@Component({
  selector: 'app-dashboard',
  template: `
    <h2>
      Dashboard component
    </h2>
    <p>
      {{myData}}
    </p>
  `,
})
export class AppDashboard implements AfterViewInit {
  myData: any;

  constructor(private sharedService: SharedService) {
          this.sharedService.cartData.subscribe(
          (data: any) => {
            console.log(data);
            this.myData = data;
          });
  }

}


@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App, AppDashboard ],
  providers: [ SharedService ],
  bootstrap: [ App ]
})
export class AppModule {}

在此处查看生命周期挂钩https://angular.io/guide/lifecycle-hooks

于 2017-07-27T13:26:16.133 回答
1

尝试这个:

export class SharedService {
    private dataPusher = new Subject<any>();
    cartData = dataPusher.asObservable().pipe(shareReplay(1));

    pushData(value:any) {
       this.dataPusher.next(value);
    }
} 

这样做是它将为“迟到的”订阅者重放最后发出的值。如果要发出初始值,可以使用BehaviourSubject- 它在构造函数中获取初始值。

或者您可以使用startWith操作员对其进行管道/链接。

cartData = dataPusher.asObservable().pipe(startWith("someValue"), shareReplay(1));
于 2018-09-05T05:00:59.330 回答