Issue with Angular BehaviourSubject which is not assignable to type error

Viewed 657

I have a simple table with angular and typescript. I am sending table data from parent class to child class(which includes the table) and in this example data name is _domainData. It is taking the data correctly but I want to show it on table and I do not know how to assign it to my main table data variable domain_Data.

As in the example: if i say this.domain_Data = this._domainData;in ngOnInit() method.

@Component({
  selector: 'mg-domain-display',
  templateUrl: './domain-display.component.html',
  styleUrls: ['./domain-display.component.scss']
})
export class DomainWhiteListingDisplayComponent implements OnInit {

  private _domainData = new BehaviorSubject<Domain[]>([]);

  displayedColumns = ['id', 'domain'];
  domain_Data: Domain[] = [];

  @Input()
  set domainData(value: Domain[]) {
    this._domainData.next(value);
  }
  get domainData() {
    return this._domainData.getValue();
  }

  constructor(private globalSettingService: GlobalSettingsService, private dialog: MatDialog) {
  }

  ngOnInit() {
    this.domain_Data = this._domainData;
  }

}

And the error is Type:BehaviourSubject is not assignable to type Domain[]. Property 'includes'is missing in type 'BehaviourSubject'

As I said my main table data variable is domain_Data:

<mat-table #table [dataSource]="domain_Data">
2 Answers

You need to subscribe and get the value from BehaviorSubject

  ngOnInit() {
    this._domainData.subscribe((data) => this.domain_Data = data);
  }

Alternatively, As few have commented, you can subscribe in the template using async pipe:

<mat-table #table [dataSource]="domain_Data | async">

Generally, if you don't need to deal with data in the component, it's best using async pipe, as it takes care of unsubscribe automatically.

I arrived a bit late but I would like to add 2 additional information about @Aragorn answer :

  • Be careful when using async pipe in the template of a component with ChangeDetectionStrategy.OnPush, as it will completly force components to trigger lifecycle detection changes as often as the default Strategy.

  • Second important info : don't forget to unsubscribe when your component is destroyed, or you will have subscription still up if you never resolve the BehaviourSubject (here you just do 'next' operations) :

subscription: ISubscription;

this.subscription = this._domainData.subscribe((data) => this.domain_Data = data);

then in onDestroy :

ngOnDestroy() {
   if (this.subscription) {
      this.subscription.unsubscribe();
   }
}
Related