vendredi 6 septembre 2019

Data Access Patterns for Angular

I'm struggling with asynchronous Data Access Patterns in an Angular 8 application (coming from .NET). I am using components, services for data access, and custom classes that act on the data from the services. It seems that I should inject my data access services into my components - but where do I leverage my custom classes for business logic?

What I'd like:

COMPONENT:

import { Component, OnInit } from '@angular/core';
import { SampleService } from '../services/sample.service';
import { CustomBusinessLogic } from '../../cbl'; 


@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.scss']
})
export class Example implements OnInit {

  constructor(private sampleService: SampleService) { }

  ngOnInit() { }

  doSomething() {

    const dataToActOn = this.sampleService.getDataToActOn();

    // Do something with dataToActOn here

      const p = new CustomBusinessLogic.Calculator(
        dataToActOn.params as Settings,
        dataToActOn.data1,
        dataToActOn.data2
      );

      const res = p.calculate();
  }
}

SERVICE:

import { Injectable } from '@angular/core';
import { ExampleDataService } from './data/example-data.service';
import { SettingsService } from './data/settings.service';
import { forkJoin } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class SampleService {

  data1: any[];
  data2: any[];
  params: [];

  constructor(private projections: ,
    private data: ExampleDataService, private settingsService: SettingsService) { }


  loadDataHttp() {

    const id = 'for-testing';
    const b = this.data.getDataSet1(new Date());
    const p = this.data.getDataSet2(new Date());
    const m = this.settingsService.getDataSet3(id, 2018);

    return forkJoin([b, p, m]);

  }

  getDataToActOn() {

    this.loadDataHttp().subscribe(data => {
      this.data1 = data[0];
      this.data2 = data[1];
      this.params = data[2];

      // HOW DO I RETURN THIS DATA TO THE COMPONENT 
      // AND HAVE IT AVAILABLE TO MY CUSTOM BUSINESS LOGIC??

    });
  }
}

My problem (in this pseudo/example code) is that when my Component gets to new CustomBusinessLogic.Calculator, none of the data has returned yet from the service.

How can I restructure this so that I can act on data returned from services in either my components or other services?

Thank you!

Aucun commentaire:

Enregistrer un commentaire