简体   繁体   中英

How to pass observable to parent component in angularjs2?

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

在此处输入图片说明

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM