Angular2 - reuse component with various services / providers

I am developing an application that has a Restful API for the backend and Angular2 for the interface.

I want to have two graphs in a view. Let's say one schedule is employee attendance, and the other is product sales. One API for each is available for receiving data from the server.

How do I plan it?

Should I have two components: one employee visit and one sales product, which in turn will use their own services and receive data and fill out the component?

OR

Should I have only one component as a “chart”? In this case, how to get the data? Is there any mechanism / good practice about services to achieve this?

I tried searching the Internet, could not get any relevant recommendations.

Please, help. Thank.

+4
source share
2 answers

Here's how I would do it, moreover, the OOP path.

Services:

export interface IGraphServices {
  getGraphData(): string;
}

@Injectable()
export class EmployeeAttendanceService implements IGraphServices {
  getGraphData(): string {
    return "Employee Attendance Data";
  }
}

@Injectable()
export class ProductSalesService implements IGraphServices {
  getGraphData(): string {
    return "Product Sales Data";
  }
}

component:

@Component({
  selector: 'graph',
  template: '<div>Graph component</div>'
})
export class GraphComponent implements OnInit {
  @Input('service') service: number;

  constructor(@Inject('IGraphServices')private providerService: IGraphServices[]) {

  }

  ngOnInit(): void {
    console.log(this.providerService[this.service].getGraphData());
  }
}

In your NgModule providers:

providers: [
    {
      provide: 'IGraphServices', useClass: EmployeeAttendanceService, multi: true
    },
    {
      provide: 'IGraphServices', useClass: ProductSalesService, multi: true
    }
]

Using:

<!-- EmployeeAttendanceService -->
<graph [service]="0"></graph>

<!-- ProductSalesService -->
<graph [service]="1"></graph>
+5
source

If it’s a good idea to build two different or one component, it’s hard to answer with the information you provided.

You can

  • enter the service in the parent element and pass it to the input of the graph component.

  • enter both services into the graph component and pass a parameter to the input, which tells the graph component which service is using

  • , , , .

  • , , . , , .

@Component({
  input: 'my-graph',
  template: ' show the graph here '
})
class MyGraphComponent {
  @Input() data;
}
  
@Component({
  input: 'employee-attendance-graph',
  template: '<my-graph [data]="data"></my-graph>'
})
class EmployeeAttendanceGraph {
  constructor(private data:Service1) {}
}
@Component({
  input: 'product-sales-graph',
  template: '<my-graph [data]="data"></my-graph>'
})
class ProductSalesGraph {
  constructor(private data:Service2) {}
}

<employee-attendance-graph></employee-attendance-graph>
<product-sales-graph></product-sales-graph>
0

Source: https://habr.com/ru/post/1654809/


All Articles