gpt4 book ai didi

angular - 从组件订阅服务中的 Observable

转载 作者:行者123 更新时间:2023-12-03 15:46:08 24 4
gpt4 key购买 nike

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

我需要了解如何正确设置我的 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$;
}

服务中的一切都按预期工作。如果我登录 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 中得到任何东西

最佳答案

你的代码有很多错误

  • 没有 this.recruiters您的服务领域
  • this.results.push(el);不会因为您使用的是 forEach(function(el){ 而对结果产生任何影响应该是 forEach((el)=>以便您的 this范围内将指代您的服务。

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

    关于angular - 从组件订阅服务中的 Observable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43124001/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com