0

Warning: I'm very new to Angular so if below question indicates that my approach is completely off the rails, please let me know.

I have a model AltChar. It has a source property which relates to a Source model. To save bandwidth, the backend does not resolve the entire Source object with all its data for each AltChar, but rather includes an id field and it transmits a list of Sources separately.

Conversely, when I update an AltChar over the API, I needn't transmit the entire Source field: the id is enough and the backend will resolve it on its side.

Here comes some code:

import { Source } from './source';

export interface AltCharInterface {
    id: number;
    source: Source | number;
    prep: any;
}

export class AltChar implements AltCharInterface {
    constructor (
        public id: number,
        public source: Source,
    ) {}

    static readonly EMPTY_MODEL = {
        id: null,
        source: Source.EMPTY_MODEL,
    } as AltChar;

    prep = () => {
        return {
            'id': this.id,
            'source': this.source.id,
        }
    };
}

Then, in my TS file, I want to transmit this data to the REST API using:

altCharService.addAltChar(this.altChar.prep())
.subscribe(data => altChars.push(this.altChar));

But it tells me that prep() is not a function.

bluppfisk
  • 2,538
  • 3
  • 27
  • 56
  • 2
    Do you have `new AltChar(...)` anywhere in your code? If not, you never construct any instance of your class, so you can't possibly have an AltChar instance and call its function (which should be a method, BTW). If you have, then post a complete minimal example reproducing the problem. – JB Nizet Aug 08 '18 at 21:34
  • you're right. They're loaded from the API so they aren't cast as an AltChar. That's the culprit. However, I'm not sure how to then cast the returned API data into an AltChar object without shovelling every property manually into the object. Or is that the way? – bluppfisk Aug 08 '18 at 21:48
  • 1
    Type hints **do not** cause casting or conversion. – jonrsharpe Aug 08 '18 at 21:48
  • I know; Elsewhere I have the script loop over all altchars and load them `data as AltChar` in the hopes of casting it into an AltChar object. Still doesn't work, and is this the right way? – bluppfisk Aug 08 '18 at 21:51
  • shovelling every property manually into the object is the way if you want to keep that design. You only have two properties, so it shouldn't be too hard. – JB Nizet Aug 08 '18 at 21:51
  • I simplified it for the question, in reality there are 10+ properties – bluppfisk Aug 08 '18 at 21:51

0 Answers0