输入Observable >不能分配给Observable类型

问题描述 投票:0回答:2

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

@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[]>错误。我怎样才能解决这个问题?

angular typescript rxjs rxjs5
2个回答
4
投票

错误说明究竟出了什么问题。你定义了:

filteredSchools: Observable<School[]>;

但是后来你创建了一个Observable,它发出(映射每个值)filterSchools(name: string): Observable<School[]>的结果,它返回一个Observable,所以最后你有一个可观察的Observable<Observable<School[]>>链。

它实际上看起来你只是想使用switchMap(或mergeMapconcatMap)而不是mapswitchMap将订阅嵌套的Observable并将链转换为Observable<School[]>

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

0
投票

我建议使用Observable.combineLatest(...)

public ngOnInit(): void {
   this.schools = this.schoolService.getSchools();

   this.filteredSchools = Observable.combineLatest(
      this.formControl.valueChanges.startWith(''),
      this.schools
   ).map(([filter, schools]) => {
       if (!filter || filter === '') {
          return schools;
       }

       return schools.filter(s => s.name.toLowerCase().includes(name));
   });
}

最后仍然有冷观察,只有当其中一个观察者发出新数据时才会触发。

不是你的问题,但对于你的模板自动完成,你需要一个displayWith功能。

© www.soinside.com 2019 - 2024. All rights reserved.