从组件订阅服务中的 Observable

Ben*_*cot 5 observable angular2-services angular2-observables angular

我已经搜索了很长时间来了解如何订阅一个值不断更新的数组。

我需要了解如何正确设置我的 Angular 2+ 服务 observable 并在我的组件中正确订阅它。请假设代码的所有其他部分都能正常工作。

@Injectable()
export class AutocompleteService {

    searchTerm: string;
    results = [];
    observe$ = Observable.from(this.results);

    searchTest(term){
        this.searchTerm = term.toLowerCase();

        if(this.searchTerm.length > 2){
            this.recruiters.forEach(function(el){
                if(el.name.toLowerCase().indexOf(term) != -1) {
                    this.results.push(el);
                }   
            });    

        }
    }

    getCurrentResults():Observable<Object> {
        return this.observe$;
    }
Run Code Online (Sandbox Code Playgroud)

服务中的一切都按预期工作。如果我登录,term我会从我的组件中获取用户输入。或者results匹配搜索结果后的数组被推送到它上面。

@Component({
    selector: 'autocomplete',
    templateUrl: './autocomplete.component.html',
    providers: [AutocompleteService]
})
export class AutocompleteComponent implements OnInit{
    constructor(private autocompleteService: AutocompleteService){}

    value: string = '';
    searchControl = new FormControl();

    // fired when input happens
    getResults(event){
        this.autocompleteService.searchTest(event.target.value);

        this.autocompleteService.getCurrentResults().subscribe(
            value => console.log(value)
        );

    }
Run Code Online (Sandbox Code Playgroud)

我已经尽我所能设置了可观察模式,但我没有从 getResults 中的 .subscribe 中得到任何东西

eko*_*eko 5

你的代码有很多错误

  1. this.recruiters您的服务中没有字段

  2. this.results.push(el);不会对结果产生任何影响,因为您forEach(function(el){应该使用它,forEach((el)=>以便您this在范围内引用您的服务。

示例 plunker:http ://plnkr.co/edit/5L0dE7ZNgpJSK4AbK0oM?p=preview


kaw*_*man 5

我补充了什么jonrsharpeechonax说:

您可以使用主题:

@Injectable()
export class AutocompleteService {

    searchTerm: string;
    results = [];
    subject = new Subject();

    searchTest(term){
        this.searchTerm = term.toLowerCase();

        if(this.searchTerm.length > 2){
            this.recruiters.forEach(el =>{
                if(el.name.toLowerCase().indexOf(term) != -1) {
                    this.subject.next(el);
                }   
            });    

        }
    }

    getCurrentResults():Subject<Object> {
        return this.subject;
    }
Run Code Online (Sandbox Code Playgroud)

}

并以getCurrentResults()与您相同的方式订阅。

你演示:plunker