角度:错误TS2322:键入' Observable< {}>'不可分配...使用share()运算符

时间:2018-05-17 07:25:22

标签: javascript angular typescript observable observer-pattern

我是Angular 5的新用户,我正在实施Observable / Observer模式,以便与订阅者共享一些事件和一些数据更改。

这里是代码片段:

...
@Injectable()
export class NidoService {
  ...
  event$: Observable<StrutturaDto[]>;
  private _observer: Observer<any>;

  event_dettaglio$: Observable<Struttura>;
  private _observer_dettaglio: Observer<any>;

  constructor() {
     this.event$ = new Observable(observer => this._observer = observer).share();
     this.event_dettaglio$ = new Observable(observer => this._observer_dettaglio = observer).share();
  }
  ...
}

当我尝试使用 ng build 构建应用程序时,我在构造函数中的两行代码中出现了这些错误:

ERROR in src/app/services/nido.service.ts(28,7): error TS2322: Type 'Observable<{}>' is not assignable to type 'Observable<StrutturaDto[]>'.
Type '{}' is not assignable to type 'StrutturaDto[]'.
Property 'includes' is missing in type '{}'.
src/app/services/nido.service.ts(29,7): error TS2322: Type 'Observable<{}>' is not assignable to type 'Observable<Struttura>'.
Type '{}' is not assignable to type 'Struttura'.
Property 'idStruttura' is missing in type '{}'.

当我在开发模式中使用它时我没有问题,但是如果不修复它我就无法构建。如何更改两行代码?

1 个答案:

答案 0 :(得分:1)

您需要指定可观察的类型:

this.event$ = new Observable<StrutturaDto[]>(observer => this._observer = observer).share();

this.event_dettaglio$ = new Observable<Struttura>(observer => this._observer_dettaglio = observer).share();