【发布时间】:2018-08-14 07:38:03
【问题描述】:
我正在使用来自数据库服务的数据实现自动完成:
@Injectable()
export class SchoolService {
constructor(private db: AngularFirestore) {
}
getSchools(): Observable<School[]> {
return this.db.collection<School>('schools').valueChanges();
}
}
在我的组件中:
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)));
}
}
还有我的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}}</small>
</mat-option>
</mat-autocomplete>
</mat-form-field>
</form>
ngOnInit 中的函数给出Type Observable<Observable<School[]>> is not assignable to type Observable<School[]> 错误。我该如何解决这个问题?
【问题讨论】:
-
@Eldho 文档说如果我在
mat-option *ngFor中使用async,Observable 将起作用,所以我不需要使用subscribe。 -
@ibenjelloun 你好,你能删除重复的标志吗?尽管标题看起来相似,但我的问题有所不同。
标签: angular typescript rxjs rxjs5