首页 > 解决方案 > 无效的对象,预期的流

问题描述

我收到此错误

类型 'never' 必须有一个返回迭代器的 'Symbol.iterator' 方法。

我知道该错误与下面代码中的 if 语句有关(drivers.service.ts)

export class DriversService {

  user: User;
  comp = '';
  constructor(private db: AngularFirestore, private auth: AuthService, private afAuth: AngularFireAuth) { }

 getUsers() {
  return this.auth.user.pipe(
    take(1),
    map(user => {
      //  user['company'];
      this.comp = user['company'];
      return user['company'];
    })
  )
 }

  findUser(value) {

    if(this.comp.length <= 0){
      return this.getUsers().subscribe(user => {
        this.comp = user;
        console.log('Bye', this.comp)
        return this.comp;
       });
    }

    let email = this.db.collection(`companies/${this.comp}/users`, ref => ref.where('email', '==', value)).valueChanges({ idField: 'id' }).pipe(
      take(1)
    );
    let name = this.db.collection(`companies/${this.comp}/users`, ref => ref.where('name', '==', value)).valueChanges({ idField: 'id' }).pipe(
      take(1)
    );
    return [email, name];
  }

并且在 forkJoin() 的 add-driver.page.ts 中显示了实际错误

export class AddDriverPage implements OnInit {
 
  users = [];
  participant = '';
  form: FormGroup;

  constructor(private driverService: DriversService, private loadingCtrl: LoadingController, private auth: AuthService) { }

  ngOnInit() {
  }

  addDriver() {
    let obs = this.driverService.findUser(this.participant);

    forkJoin(obs).subscribe(res => {
      for (let data of res) {
        if (data.length > 0) {
          this.users.push(data[0]);
        }
      }
      console.log('it works:', this.participant)
      this.participant = '';
    });

  }
}

那么我该如何解决这个问题呢?

标签: javascriptangulartypescriptfirebaseionic-framework

解决方案


更改您的服务功能:

if (this.comp.length <= 0) {
      return [this.getUsers().pipe(map(user => {
        this.comp = user;
        console.log('Bye', this.comp);
        return this.comp;
       }))];
    }

然后在您的组件中:

addDriver() {
    const obs = this.driverService.findUser(this.participant);

    forkJoin(obs).subscribe(res => {
      if (!res || !res.length) {
        return console.log('Got undefined');
      }
      for (let data of res) {
        if (data.length > 0) {
          this.users.push(data[0]);
        }
      }
      console.log('it works:', this.participant)
      this.participant = '';
    }, error => {
   console.log('Here you got an error: ', error);
});
  }

推荐阅读