Browse Source

FactoryService使用

可以使用useFactory設定條件,來使用不同的Service
master
HarveyMac 2 years ago
parent
commit
d8c39876e6
  1. 18
      src/app/app.module.ts
  2. 18
      src/app/order-anniversary.service.ts

18
src/app/app.module.ts

@ -4,16 +4,24 @@ import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { OrderService } from './order.service';
import { OrderDiscountService } from './order-discount.service';
import { OrderAnniversaryService } from './order-anniversary.service';
@NgModule({
imports: [BrowserModule, FormsModule],
declarations: [AppComponent],
providers: [{
providers: [
{
provide: OrderService,
useValue:{computeTotal:()=>100},
},],
useFactory: () => {
const today = new Date(2020, 9, 3);
if (today.getMonth() === 9) {
return new OrderAnniversaryService();
} else {
return new OrderService();
}
},
},
],
bootstrap: [AppComponent],
})
export class AppModule {}

18
src/app/order-anniversary.service.ts

@ -0,0 +1,18 @@
import { Injectable } from '@angular/core';
import { OrderDetail } from './order-detail';
@Injectable({
providedIn: 'root',
})
export class OrderAnniversaryService {
details: OrderDetail[] = [];
constructor() {}
computeTotal(): number {
return this.details
.map((d) => d.PurchaseCount * d.UnitPrice * 0.8)
.reduce((act, curr) => act + curr, 0);
}
}
Loading…
Cancel
Save