Typescript认为响应数组是一个对象

时间:2017-12-20 17:58:56

标签: javascript angular typescript

我有一个Observable流,显然会将一个数组输出到subscribe块中。我试图将响应分配给数组变量以呈现自动完成结果。除了打字稿错误外,一切正常。

自动填充组件:

<main>

父组件:

@Component({
  selector: 'auto-complete',
  styleUrls: ['auto-complete.component.scss'],
  template: `
    <div class="ac-container">
      <div class="ac-input">
        <input type="text" [(ngModel)]="query" (keyup)="filter()">
      </div>
      <div class="ac-results" *ngIf="results.length > 0">
        <ul *ngFor="let item of results">
          <li>
            <a (click)="select(item)">{{item}}</a>
          </li>
        </ul>
      </div>
    </div>
  `
})

export class AutoCompleteComponent {
  @Input() fn: Function;

  public query = '';
  public results = [];

  filter() {
    let value = Observable
      .from(this.query)
      .throttleTime(20)
      .map(value => value)
      .distinctUntilChanged()
      .map(search => this.fn(search))
      .switch()
      .subscribe(response => {
        this.results = response;
      }, error => {}
    );
  }
}

错误:

enter image description here

IED错误指示:

enter image description here

我希望我可以展示我尝试的事情的例子,但我所做的只是谷歌搜索。我不知道。感谢。

编辑/添加

假DB / Http响应

从'@ angular / core'导入{Injectable};

@Component({
  selector: 'auto-completor',
  template: `<auto-complete [fn]="apiSearch"></auto-complete>`
})

export class AppComponent implements OnInit {
  public results: any;

  constructor(
    private service: AppService
  ) {}

  public apiSearch(term) {
    return this.service.getSearchData(term);
  }

  ngOnInit() {
    this.apiSearch = this.apiSearch.bind(this);
  }
}

App Service将承诺回复转换为Observable

@Injectable()
export class Database {
  private FAILURE_COEFF = 10;
  private MAX_SERVER_LATENCY = 200;

  private getRandomBool(n) {
    var maxRandomCoeff = 1000;
    if (n > maxRandomCoeff) n = maxRandomCoeff;
    return Math.floor(Math.random() * maxRandomCoeff) % n === 0;
  }

  public getSuggestions(text) {
    var pre = 'pre';
    var post = 'post';
    var results = [];
    if (this.getRandomBool(2)) {
      results.push(pre + text);
    }
    if (this.getRandomBool(2)) {
      results.push(text);
    }
    if (this.getRandomBool(2)) {
      results.push(text + post);
    }
    if (this.getRandomBool(2)) {
      results.push(pre + text + post);
    }

    return new Promise((resolve, reject) => {
      var randomTimeout = Math.random() * this.MAX_SERVER_LATENCY;
      setTimeout(() => {
        if (this.getRandomBool(this.FAILURE_COEFF)) {
          reject();
        } else {
          resolve(results);
        }
      }, randomTimeout);
    });
  }
}

1 个答案:

答案 0 :(得分:1)

问题是Observable没有输入,因为你的函数fn没有调用签名。我现在无法检查它,但如果你给fn一个lambda表达式调用签名,observable可能会接管它的类型,使你能够将它分配给结果。

@Input() fn: (string) => string[];

或者,您可以按任意方式键入结果,但这只是一种快速且非常脏的解决方法,可以完全删除类型。