Working on implementing autocomplete using data from a database service:
@Injectable()
export class SchoolService {
constructor(private db: AngularFirestore) {
}
getSchools(): Observable<School[]> {
return this.db.collection<School>('schools').valueChanges();
}
}
In my component:
export class SchoolComponent implements OnInit {
formControl: FormControl = new FormControl();
schools: Observable<School[]>;
filteredSchools: Observable<School[]>;
constructor(private schoolService: SchoolService) {
}
ngOnInit() {
this.schools = this.schoolService.getSchools();
//Encountering error "Type Observable<Observable<School[]>> is not assignable to type Observable<School[]>" with the line below.
this.filteredSchools = this.formControl.valueChanges.pipe(
startWith(''),
map(name => this.filterSchools(name))
);
}
filterSchools(name: string): Observable<School[]> {
return this.schools.map(school => school.filter(s => s.name.toLowerCase().includes(name)));
}
}
Here's the corresponding html code:
<form>
<mat-form-field>
<input type="text" matInput placeholder="Type Your School to Continue" [matAutocomplete]="auto"
[formControl]="formControl">
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let school of filteredSchools | async" [value]="school">
<span>{{school.name}}</span> |
<small>{{school.city}}</small>
</mat-option>
</mat-autocomplete>
</mat-form-field>
</form>
The issue causing
Type Observable<Observable<School[]>> is not assignable to type Observable<School[]>
error is in the ngOnInit
function. How should I resolve this?