Marksman
Marksman

Reputation: 125

How to pass observable to parent component in angularjs2?

I've got two components, SearchComponent and RuleListComponent. Search is children of RuleList.

enter image description here

I want SearchComponent to use APIService to download data. This data have to be passed to RuleList in observable.

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());
  }
}

How can I keep passing data from SearchComponent to RuleListComponent asynchronously depending on changing term?

Upvotes: 0

Views: 579

Answers (1)

Poul Kruijt
Poul Kruijt

Reputation: 71891

A good idea would be to make a SearchService and have both RuleListComponent and SearchComponent inject this service.

Then have SearchService inject the ApiService and set the items inside the SearchService and not in your component. Components should not be used for storing data

Upvotes: 2

Related Questions