我在传递数据时收到以下错误
Property 'id' does not exist on type '{}'.
这是我的代码
- 服务 *
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable, Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class SidePanelAccordianService {
private _openStateBehaviorSubject = new BehaviorSubject({});
public openState$ = this._openStateBehaviorSubject.asObservable();
public setOpenState(data: { id: string, state: boolean }) {
this._openStateBehaviorSubject.next(data);
}
}
- TS *
import { Component, Input, OnInit } from '@angular/core';
import { SidePanelAccordianData } from './side-panel-accordian.model';
import { SidePanelAccordianService } from './side-panel-accordian.service';
@Component({
selector: 'app-side-panel-accordian',
templateUrl: './side-panel-accordian.component.html',
styleUrls: ['./side-panel-accordian.component.scss']
})
export class SidePanelAccordianComponent implements OnInit {
@Input() data: SidePanelAccordianData;
panelOpenState;
constructor(private accordianStateService: SidePanelAccordianService) { }
ngOnInit(): void {
}
stateValue() {
this.data.panelOpenState = !this.data.panelOpenState;
this.accordianStateService.setOpenState({ id: this.data.id, state: this.data.panelOpenState });
}
}
- 型号 *
export class SidePanelAccordianData {
public id?: string = '';
public title: string = '';
public panelOpenState: boolean;
public expanded: boolean;
constructor(args) {
this.id = args.id;
this.title = args.title;
this.panelOpenState = args.panelOpenState;
this.expanded = args.expanded;
}
}
- HTML *
<mat-accordion>
<mat-expansion-panel (id)="data.id" (opened)="data.panelOpenState === true" (closed)="data.panelOpenState === false" [expanded]="data.expanded" (click)="stateValue()">
<mat-expansion-panel-header>
<mat-panel-title>
{{ data?.title }}
</mat-panel-title>
</mat-expansion-panel-header>
<ng-content></ng-content>
</mat-expansion-panel>
</mat-accordion>
- 出现错误的组件 *
this.accordianStateService.openState$.subscribe(data => {
if (data.id === 'firstAccordionId') {
this.firstDriverExpanded = true;
} else if (data.id === 'secondAccordionId') {
this.secondDriverExpanded = false;
} else if (data.id === 'secondAccordionId') {
this.thirdDriverExpanded = false;
}
});
如果我console.log(data)
,那么我得到{}
。如何在订阅之前设置对象中的值?
2条答案
按热度按时间2ic8powd1#
或
oxcyiej72#
您必须按照以下方式配置
_openStateBehaviorSubject
:这将指定BehaviorSubject的泛型类型。如果不传递它,泛型类型将只是
{}
作为默认值,这就是错误的原因。