Cannot invoke an expression whose type lacks a call signature. Type ‘ItemModel’ has no compatible call signatures.
我正在使用BehaviorSubject和Subject在两个不同的状态之间共享一个集合Item.基本上,我想设置一个选定的项目,然后,当转到其详细信息页面时,获取它.
这是我的item.model.ts,我们假设它只有一个id属性:
export class ItemModel { public id: string; constructor( id: string ) { this.id = id; } }
这是我的item.service.ts用来获取和设置一个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(); } }
我的item.component.ts将设置一个给定的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]); } }
在details.page.ts上我想得到那个项目:
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)); } }
到目前为止我在调用setter时尝试了什么:
> item作为ItemModel
> item作为typeof ItemModel
>来自this answer by @Sefe等的其他解决方案
>检查在Typescript的GitHub问题like this one上打开的很多问题
我究竟做错了什么?如何确保ItemModel具有兼容的签名?
编辑
在@ n00dl3的帮助下,我能够摆脱这个错误.但是,不幸的是,当记录详细信息时.page.ts的ngOnInit我得到null.当我在setter中登录时,它会显示正确的输出.
解决方法
this._itemService.item = item;
Defining a setter on new objects in object initializers This will
define a pseudo-property current of object language that,when
assigned a value,will update log with that value:06001
对于null vs item问题:
这是因为您不应该在组件内声明您的服务,而是在NgModule中声明(因此您应该从组件提供程序中删除它):
@NgModule({ imports:[CommonModule],declarations:[SomeComponent],providers:[ItemService] }) export class myModule{}
当您在组件的提供者中声明服务时,它仅对该组件可用,dirrectives应用于它及其子组件. (更多细节见于this question.)因此,这意味着您当前没有在DetailsPage和ItemComponent中与同一服务实例进行通信.