Hejka, napisałem prostą dość apkę: https://github.com/Mateuszto/countries/tree/master/src/app
Czy jest jakaś szansa na wykorzystanie w tym serwisów?
Dzięki za pomoc!
Implementacja serwisów w angularze - Pomoc
- Rejestracja: dni
- Ostatnio: dni
- Lokalizacja: Poznań
- Postów: 163
0
- Rejestracja: dni
- Ostatnio: dni
- Postów: 219
0
W sumie jak już stworzyłeś serwis o nazwie countries to wypada przenieść tam funkcję getCountry i w razie potrzeby załadować serwis do danego komponentu :)
W przypadku getContinent nie przenosiłbym tam, bo nazwa serwisu nie mówi nam za bardzo, że akurat kontynenty też tam znajdziemy. Chyba, że tak zakładasz, ale wtedy zmieniłbym jednak nazwę serwisu
- Rejestracja: dni
- Ostatnio: dni
- Lokalizacja: Poznań
- Postów: 163
0
@Kondziowsky: @Kondziowsky:
Dałem teraz tak:
App.component
getCountry(country: string) {
this.countriesService.getCountry(country);
}
Serwis
allCountries: ICountries[] = Countries;
constructor() {
}
getCountry(country: string) {
if(country){
this.allCountries = this.allCountries.filter(element => element.country.includes(country));
} else {
this.allCountries = Countries;
}
}
No i coś się wykrzaczyło :/
- Rejestracja: dni
- Ostatnio: dni
- Postów: 219
0
Blisko, ale jak już przerabiasz dane w serwisie to zwróć je za pomocą return :)
A jak już return będzie to w Twoim komponencie musisz przypisać gdzieś dane (stwórz sobie zmienną)
czyli np:
const country = this.countriesService.getCountry(country);
getCountry(country: string) {
let tempVar;
country ? tempVar = this.allCountries.filter(element => element.country.includes(country)) : tempVar = Countries;
return tempVar;
}
lub wg Twojej wersji z ifem:
getCountry(country: string) {
if(country){
return this.allCountries.filter(element => element.country.includes(country));
} else {
return Countries;
}
}
- Rejestracja: dni
- Ostatnio: dni
- Lokalizacja: Poznań
- Postów: 163
0
@Kondziowsky:
Końcowo
Serwis:
export class CountriesService {
allCountries: ICountries[] = Countries;
constructor() {
}
getCountry(country: string) {
if(country){
return this.allCountries.filter(element => element.country.toLowerCase().includes(country));
} else {
return Countries;
}
}
}
Component:
export class AppComponent implements OnInit {
allCountries: ICountries[] = Countries;
constructor(private countriesService: CountriesService) { }
ngOnInit(): void {
}
getContinent(continent: string){
this.allCountries = Countries;
if(continent === 'World'){
this.allCountries = Countries;
} else {
this.allCountries = this.allCountries.filter(country => country.continent === continent);
}
}
getCountry(country: string){
this.allCountries = this.countriesService.getCountry(country);
console.log(this.countriesService.getCountry(country));
}
}