When I attempt to set a new Item
, I am encountering the following error as per the title:
Cannot invoke an expression whose type lacks a call signature. Type 'ItemModel' has no compatible call signatures.
To share a selected Item
between different states, I am utilizing BehaviorSubject
and Subject
. Essentially, my goal is to set a chosen Item
and then retrieve it when navigating to its details page.
In my item.model.ts
, let's assume it only contains an id
property:
export class ItemModel {
public id: string;
constructor( id: string ) {
this.id = id;
}
}
Here's how my item.service.ts
is used to get
and set
an Item
:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { ItemModel } from './item.model';
@Injectable()
export class ItemService {
public _item = new BehaviorSubject<ItemModel>(null);
item$ = this._item.asObservable();
public set item(item: ItemModel) {
this._item.next(item);
}
public get item() : ItemModel {
return this._item.getValue();
}
}
My item.component.ts
sets a specific Item
:
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { ItemService } from '../item.service';
@Component({
selector: 'app-item',
templateUrl: './item.html',
styleUrls: ['./item.scss'],
providers: [ItemService]
})
export class ItemComponent {
constructor(private _router: Router, private _itemService : ItemService) { }
goToDetails(item : ItemModel){
this._itemService.item = item; //Throws the error
this._router.navigate(['/details', item.id]);
}
}
In the details.page.ts
, I aim to retrieve that Item
:
import { Component } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { ItemService } from './item.service';
import { ItemModel } from './item.model';
@Component({
selector: 'app-details-page',
templateUrl: './details.page.html',
styleUrls: ['./details.page.scss'],
providers: [ItemService]
})
export class DetailsPage {
private _item: ItemModel;
private subscription: Subscription;
constructor( private _itemService: ItemService ) { }
ngOnInit() {
this.subscription = this._itemService.item$
.subscribe(item => console.log(item));
}
}
Various attempts have been made to resolve the issue with invoking the setter method, including casting types and exploring different solutions mentioned in Stack Overflow threads and TypeScript GitHub issues.
If you can help identify what I'm doing wrong and suggest how to ensure ItemModel has a compatible signature, it would be greatly appreciated!
UPDATE
Thanks to assistance received, the initial error has been addressed. However, there persists an issue where the logged output inside ngOnInit
of details.page.ts
shows null
, despite the correct output being displayed inside the setter.