In our car part example, we are using mock file for data loading. Actually this is not a very good solution because we need to import mock in every file that need the data. Also, it is not easy to switch between real and mock data. This sort of data loading is best left to service classes.
Let create the simplest service by creating racing-data.services.ts. The flow will be car-parts.component.ts -> racing-data.services.ts -> mock.ts.
Here is our racing-data.services.ts:
import { CARPARTS } from './mocks';
export class RacingDataService {
getCarParts() {
return CARPARTS ;
}
}
Our car-part.component.ts will lookup the new created racing-data.service.ts instead of mock.ts.
...
import { RacingDataService } from './racing-data.service';
...
export class CarPartComponent {
...
ngOnInit() {
let racingDataService = new RacingDataService();
this.racingDataService.getCarParts()
}
...
}
Download Car Part Source:
https://github.com/htsiah/angular2-carparts
No comments:
Post a Comment