Angular 2 - Typescript Test Database Base Class
I am learning Angular 2 and playing with a sandbox project and I 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 MockDatabase class like:
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 this class in a service class like this:
@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 the error "No provider for MockDatabase", but if I add it as a provider in RestaurantsComponent I get another error: "No provider for Array ()", so I think I am doing something wrong here ,
I believe that I may have a fundamental misunderstanding of how you should design such things in Angular 2, since I am completely new to web development in general.
Any help or pointers in the right direction would be appreciated as I am having trouble finding a good resource online. Thank you so much for your time.
source to share
So I solved the problem by playing around with it a bit. I realized that having a private field in the constructor implies it is injected, so I have to declare it as a regular instance variable inside the class. This is how it looks now that someone is asking a question with a similar problem.
export class MockDatabase {
private list: Restaurant[]
constructor(){
this.list = new Array();
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
@Injectable()
export class RestaurantsService {
private db: MockDatabase;
constructor(){
this.db = new MockDatabase();
}
getAllRestaurants(): Restaurant[] {
return this.db.getList();
}
}
The RestaurantsComponent class remains the same.
source to share