如何在angularjs2中将observable传递给父组件?

时间:2016-10-06 12:29:40

标签: angular typescript angular2-components

我有两个组件,SearchComponent和RuleListComponent。 搜索是RuleList的子项。

enter image description here

我希望SearchComponent使用API​​Service下载数据。 必须将此数据传递给可观察的RuleList。

的SearchComponent:

export class SearchComponent implements OnInit {
  items: Observable<Array<string>>;
  term = new FormControl(); # term is async

  constructor(private apiService: APIService) { }

  ngOnInit() {
    this.items = this.term.valueChanges
      .debounceTime(1000)
      .distinctUntilChanged()
      .switchMap(term => this.apiService.fetch('rule', term));
  }
}

APIService:

@Injectable()
export class APIService {
  baseUrl: string;

  constructor(private http: Http) {
    this.baseUrl = '//127.0.0.1:8000/';
  }

  fetch(term: string) : Observable<any> {
    console.log('searching');
    var search = new URLSearchParams();
    search.set('search', term);
    return this.http.get(this.baseUrl, { search })
                    .map(response => response.json());
  }
}

如何根据更改的术语,异步地将数据从SearchComponent传递到RuleListComponent?

1 个答案:

答案 0 :(得分:2)

一个好主意是制作一个Warning: Task "stylelint:src" failed. Use --force to continue.并同时SearchServiceRuleListComponent注入此服务。

然后让SearchComponent注入SearchService并将项目设置在ApiService内,而不是在您的组件中。组件不应用于存储数据