-
Notifications
You must be signed in to change notification settings - Fork 0
task#07 auction data service
bacn edited this page Sep 16, 2020
·
1 revision
- Create a
AuctionDataServicein the shared folder - Create a method
getAuctions()that returns an array of Auctions - Load the data from the
AuctionDataServicethrough the DI into the classAuctionListComponent - Extend the providers array (use the option locally in the class
AuctionListor globally in@NgModule)
Compile and start the application with
$ ng serve
- Open your browser with the address http://localhost:4200/
- You should see all three auction titles
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
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;
}
}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();
}
...
...
}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 { }