0

Service:

getGroups():Observable<Group[]> {

    return this._http.get(this.url).map((res: Response) => res.json());
}

Class:

export class Group {
    id: number;
    name: string;
    vat: string;

    items: Item[];

    addItem = function(item: Item): void{
        this.items.push(item);
    }
}

Component:

groups:Group[];
selectedGroup:Group;

onSelectGroup(currentGroup:Group):void {
    this.selectedGroup = currentGroup;
}

ngOnInit():void {

    this.groupService.getGroups().subscribe(groups => this.groups = groups);

}

Template:

    <div *ngFor="let g of groups" [class.selected]="g === selectedGroup">

                    <button (click)="onSelectGroup(g)">Select group</button>

</div>

When I try to use the method (on a single array element - group of course) addItem(ItemObject) it says "this.selectedGroup.addItem is not a function".

Help please

draco
  • 21
  • 3
  • the rest of properties I can get without problems. The only thing I lose is the method.. why? – draco Dec 09 '16 at 07:40
  • where is your `selectedGroup` defined ? show more code please – Pardeep Jain Dec 09 '16 at 07:41
  • Because you haven't actually converted the JSON to that object. – jonrsharpe Dec 09 '16 at 07:44
  • return this._http.get(this.url).map((res: Response) => res.json() as Group); - this does not help; return this._http.get(this.url).map((res: Response) => res.json() as Group[]); - this neither – draco Dec 09 '16 at 07:47
  • Casting to a type doesn't change anything. You just tell the tools (IDE) that statically analyze your code that it's safe to assume this value is of type `Group` but is just ignored at runtime (as all type information is) – Günter Zöchbauer Dec 09 '16 at 07:48

0 Answers0