I am learning Angular 2 and playing around with a sandbox project, and was wondering how to use a class in another class similar to how you would in Java or other OOP languages.
If i have a class MockDatabase like so:
export class MockDatabase {
constructor(private list: Restaurant[]){
this.list.push({ id: 1, name: "Chinese", tags: ["Chinese"] });
this.list.push({ id: 2, name: "Mexican", tags: ["Mexican"] });
this.list.push({ id: 3, name: "Italian", tags: ["Italian"] });
this.list.push({ id: 4, name: "American", tags: ["American"] });
}
getList(): Restaurant[] {
return this.list;
}
}
and I want to use that class in a service class like so:
@Injectable()
export class RestaurantsService {
constructor(private db: MockDatabase){
}
getAllRestaurants(): Restaurant[] {
return this.db.getList();
}
}
which is then used in this component:
@Component({
selector: 'restaurants',
templateUrl: 'restaurants.html',
providers: [RestaurantsService, PreferencesFilterService]
})
export class RestaurantsComponent implements OnInit{
restaurants: Restaurant[];
constructor(
private restaurantsService: RestaurantsService,
private preferencesFilterService: PreferencesFilterService
) {}
ngOnInit(): void {
this.restaurants = this.restaurantsService.getAllRestaurants();
}
filterRestaurants(): void {
this.restaurants = this.preferencesFilterService.getFilteredRestaurants();
}
I get an error saying "No provider for MockDatabase," but then if I add it as a provider to the RestaurantsComponent I get another error saying "No provider for Array()," so I think I am doing something wrong here.
I believe I may have a fundamental misunderstanding of the way you are supposed to design things like this in Angular 2 as I am brand new to web development as a whole.
Any help or pointers in the right direction would be greatly appreciated, as i was having trouble finding a good resource online. Thank you very much for your time.