从组件订阅服务中的 Observable

Subscribing to Observable in service from component

我搜索了相当长一段时间才明白如何订阅一个值不断更新的数组。

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

@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$;
    }

服务中的一切都按预期工作。如果我记录 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)
        );

    }

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

你的代码有很多错误

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

  2. this.results.push(el); 不会对结果产生任何影响,因为你正在使用 forEach(function(el){ 它应该是 forEach((el)=> 这样你的 this 就在里面范围将参考您的服务。

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

我除了jonrsharpe and echonax说的:

您可以使用主题:

@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;
    }

}

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

你演示:[​​=13=]