我不知道subject对象如何为我试图在angular2中实现的建议/搜索服务工作。
假设每次输入更改时都会调用GenerateSuggestions,以供自动完成使用。
我不明白为什么我不能从“next()”调用中得到一些东西,typescript编译器说它返回了一个void类型。
我的目标是将每个更改提交给一个对象,该对象将决定在服务器上每500毫秒调用一个函数,而不会在每个键条目上散布它。

import { Jsonp, Response, Http } from 'angular2/http';
import * as Rx from 'rxjs/Rx';
import { Injectable } from 'angular2/core';

@Injectable()
export class SearchService {
    queryStream = new Rx.Subject();

    constructor(public http: Http) {

    }

    generateSuggestions(query: string) {
        this.queryStream
            .next(query)
            .debounce(500) // Compiler error: Debounce does not exist on type "void"
            .map(
                query => this.http.get('hellow')
                        .map( (res: Response) => res.json() )
                        .subscribe( results => console.log(results) )
            );
    }
}

我可以用普通的js/typescript来实现,但我真的想尝试使用rxjs,因为它已经被angular2使用了。
这里犯了什么错误?在他们的官方网站上,没有任何例子,文件真的很差。

最佳答案

注意:如果你有更好的选择,只需发布另一个答案,我会选择它作为答案。
我的研究结果表明,我对治疗对象的目的没有很好的理解。
使用ngmodel和ngmodelchange的建议解决方案
因为我目前只在组件中使用ngmodel,所以我必须将[(ngmodel)]拆分为[ngmodel]和(ngmodelchange)
在组件构造函数中
使用一个rx.subject(理论上它与eventEmitter相同,但可能因为我们不再有权使用它访问所有rx.subject方法而改变了),它将被参数化为去缓冲并调用服务来检索值。
每次按键:
输入->(ngmodelchange)->eventemittercomponentinstance.next(inputValue)
代码
建议多字符串组件.ts

@Component({
  template: `<input [ngModel]="userInput"
                    (ngModelChange)="userInputChanged($event)" />`
  providers: [SearchService]
})
export class SuggestMultipleStringComponent {
    private typeAheadEventEmitter = new Rx.Subject<string>();
    private userInput: string;

    constructor(private _searchService: SearchService) {
        this.typeAheadEventEmitter
                .debounceTime(700)
                .switchMap(val => {
                    console.log('called once')
                    return this._searchService.callSomething();
                }).subscribe(results => {
                    console.log(results);
                }, error => {
                    console.log('error logged:');
                    console.log(error);
                });
      }

    userInputChanged(value: string) {
        this.userInput = value;
        this.typeAheadEventEmitter.next(value);
    }
}

搜索服务.ts
@Injectable()
export class SearchService {

    constructor(private http: Http) {
        this.http = http;
    }

    callSomething() {
        return this.http.get('some/url')
                        .map((res: Response) => res.json());
    }
}

09-20 21:27