angular - Typen Observable<Observable<any[]>> kan inte tilldelas till typen Observable<any[]>
Jag implementerar automatkomplettering med data från databastjänst:
@Injectable()
export class SchoolService {
constructor(private db: AngularFirestore) {
}
getSchools(): Observable<School[]> {
return this.db.collection<School>('schools').valueChanges();
}
}
I min komponent:
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();
//Below line gives error "Type Observable<Observable<School[]>> is not assignable to type Observable<School[]>".
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)));
}
}
Och min html:
<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}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</form>
Funktionen i ngOnInit ger felet Type Observable<Observable<School[]>> is not assignable to type Observable<School[]>. Hur kan jag åtgärda detta?
Svar #1
Felet säger exakt vad som är fel. Du har definierat:
filteredSchools: Observable<School[]>;
men senare skapar du en Observable som sänder (mappas varje värde) resultaten av filterSchools(name: string): Observable<School[]> som också returnerar en Observable, så i slutändan har du en Observable-kedja av Observable<Observable<School[]>>.
Det ser faktiskt ut som att du bara ville använda switchMap (eller mergeMap eller concatMap) istället för map. switchMap kommer att prenumerera på den inneslutna Observable och förvandla kedjan till Observable<School[]>:
this.filteredSchools = this.formControl.valueChanges.pipe(
startWith(''),
switchMap(name => this.filterSchools(name))
);
