gpt4 book ai didi

angular - 类型 Observable> 不可分配给类型 Observable

转载 作者:搜寻专家 更新时间:2023-10-30 21:17:24 27 4
gpt4 key购买 nike

我正在使用来自数据库服务的数据实现自动完成:

@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[]>错误。我该如何解决这个问题?

最佳答案

错误准确地说明了问题所在。您定义了:

filteredSchools: Observable<School[]>;

但稍后您创建了一个 Observable,它发出(映射每个值)filterSchools(name: string): Observable<School[]> 的结果它也返回一个 Observable,所以最后你有一个 Observable 链 Observable<Observable<School[]>> .

实际上看起来您只是想使用 switchMap (或 mergeMapconcatMap )而不是 map . switchMap将订阅嵌套的 Observable 并将链变为 Observable<School[]> :

this.filteredSchools = this.formControl.valueChanges.pipe(
startWith(''),
switchMap(name => this.filterSchools(name))
);

关于angular - 类型 Observable<Observable<any[]>> 不可分配给类型 Observable<any[]>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49130956/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com