Skip to content

task#07 auction data service

bacn edited this page Sep 16, 2020 · 1 revision

Create an AuctionData service

  1. Create a AuctionDataService in the shared folder
  2. Create a method getAuctions() that returns an array of Auctions
  3. Load the data from the AuctionDataService through the DI into the class AuctionListComponent
  4. Extend the providers array (use the option locally in the class AuctionList or globally in @NgModule)

Result

Compile and start the application with

$ ng serve

Hints

Generate with ng-cli:

$ ng generate service shared/auction-data

Source files containing elements, which are use by several other components or classes shall be moved to folders with name shared.

src
\- main.ts
\- app
   \- auction-list
      \- auction-list.component.css
      \- auction-list.component.html
      \- auction-list.component.ts
      \- auction-list. component spec.ts
   \- shared
      \- auction.ts
      \- auction-data.service.ts
      \- auction-data.service.spec.ts
      \- auction-data.ts
   \- app.module.ts
   \- app.component.ts
   \- index.html

auction-data.service.ts

The auction-data.service needs a private variable auctions of type Auction[] plus a public getter.

import {Auction} from './auction';
import {AUCTION_DATA} from './auction-data';
import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';

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

    private auctions: Auction[] = AUCTION_DATA;

    constructor(private http: HttpClient) {
    }

    public getAuctions() {
        return this.auctions;
    }
}

auction-list.component.ts

The auction list component needs a constructor with an AuctionDataService. The service is automatically injected by the dependency injection of Angular.

export class AuctionListComponent implements OnInit {
  @Input() headerTitle: string;
  @Output() titleClicked = new EventEmitter<string>();

  auctions: Auction[];

  constructor(private auctionDataService: AuctionDataService) {
    this.auctions = auctionDataService.getAuctions();
  }
...
...
}

app.module.ts

The AuctionDataService is implicitly providedIn:root? added and HttpClientModule is added as a imports to the @NgModule class.

@NgModule({
  declarations: [
    AppComponent,
    AuctionListComponent,
    MouseEventDisplayComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Clone this wiki locally