Handling related models in Angular

Discussão em 'Angular' iniciado por bbricker87, Dezembro 15, 2024.

  1. bbricker87

    bbricker87 Guest

    I'm trying to figure out the correct way to handle related models. Our api returns each model with ids to any other model it is linked to.

    Api Responses


    // api/contracts
    {
    contracts: [{
    id: 1
    client_id: 1
    salesman_id: 1
    }, {
    id: 1
    client_id: 1
    salesman_id: 1
    }]
    }

    // api/clients
    {
    clients: [{
    id: 1,
    name: 'Company 1'
    }]
    }

    // api/salesmen
    {
    salesmen: [{
    id: 1,
    name: 'John Smith'
    }]
    }

    Angular Model Classes


    export class Contract {
    id: number;
    client_id: number;
    salesman_id: number;

    client: Client;
    salesman: Salesman;
    }
    export class Client {
    id: number;
    name: string;
    }
    export class Salesman {
    id: number;
    name: string;
    }


    I'm able to get the initial data using the angular httpClient, but cannot find a way to get the related models. This works to grab one of the related models, but I can't see this being the correct way with any models that have more than one related model.

    Angular Contract Service


    export Class ContractService {
    getAll(): Observable<Contract[]> {
    return this.httpClient.get(API_URL + '/contracts').pipe(
    map(data => data.contracts as Contract[]),
    flatMap((contracts: Contract[]) => forkJoin(contracts.map((contract: Contract) => {
    return this.salesmanService.get(contract.salesman_id).pipe(
    map((salesman: Salesman) => {
    contract.salesman = salesman;
    return contract;
    })
    );
    })))
    );
    }

    Component Template


    <table>
    <thead>
    <tr>
    <th>ID</th>
    <th>Client</th>
    <th>Salesman</th>
    </tr>
    </thead>
    <tbody>
    <tr *ngFor='let contract of contracts$ | async'>
    <td>{{contract.id}}</td>
    <td>{{contract.client.name}}</td>
    <td>{{contract.salesman.name}}</td>
    </tr>
    </tbody>
    </table>


    So I'm wondering if anyone has suggestions on how to handle larger models while using observables.

    Our previous application used EmberJS and our API is setup to interface with Ember-Data. So I may be stuck in an Ember way of thinking, but I'm hoping someone else has dealt with this before.

    Continue reading...

Compartilhe esta Página