Tips for transferring observable to parent component in angular 2?

I have two components, SearchComponent and RuleListComponent. The Search component is a child of RuleList.

https://i.stack.imgur.com/rFlM2.png

I need the SearchComponent to retrieve data using APIService. This data should then be passed to RuleList as an observable.

SearchComponent:

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

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

Is there a way to continuously pass data from SearchComponent to RuleListComponent based on changing terms asynchronously?

Answer №1

A great suggestion is to create a separate `SearchService` and have both the `RuleListComponent` and `SearchComponent` depend on this service.

It would be ideal for the `SearchService` to also rely on the `ApiService` and handle setting the items internally rather than in the component itself. It's best practice to avoid storing data directly within components.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to scroll a specific element within a div container?

I need to enable horizontal scrolling on the user-selected content within a specific div by utilizing its ID. Here is the HTML code snippet: <ion-scroll #scroll scrollX="true" style="height:85px; border-bottom: 2px solid #a01e1e;"> <div class="s ...

Please provide TypeScript code for a React wrapper function that augments a component's props with two additional functions

During the course of my project, I implemented a function wrapping React component to incorporate undo/redo functionality using keyboard shortcuts Ctrl+Z and Shift+Ctrl+Z. Here is an example: import React from 'react'; interface WithUndoRedoProp ...

The Angular module does not have any exported member named 'ButtonFillMode'

Encountering an error message stating '"@progress/kendo-angular-buttons"' has no exported member 'ButtonFillMode'. when utilizing the Kendo Editor toolbar module. Despite having installed all necessary dependencies for the Edi ...

Building a Dynamic Video Element in Next Js Using TypeScript

Is there a way to generate the video element in Next JS using TypeScript on-the-fly? When I attempt to create the video element with React.createElement('video'), it only returns a type of HTMLElement. However, I need it to be of type HTMLVideoEl ...

How can an Angular4 unit test disregard an HTML tag from a third-party component?

I've exhausted my resources by checking the docs, SO, and attempting various solutions, but I am unable to make this work. The issue arises when writing a unit test for an angular4 application using karma/jasmine. The test is targeting a component tha ...

What is the best way to link labels with input fields located separately in Angular?

Imagine a scenario where labels and form fields are being created in a *ngFor loop, as shown below: app.component.ts export class AppComponent { items = ['aaa', 'bbbbbb', 'ccccccccc'] } app.component.html <div class ...

Set up your Typescript project to transpile code from ES6 to ES5 by utilizing Bable

Embarking on a new project, I am eager to implement the Async and Await capabilities recently introduced for TypeScript. Unfortunately, these features are currently only compatible with ES6. Is there a way to configure Visual Studio (2015 Update 1) to co ...

Is Angular equipped with named routes or states similar to UIRouter?

When working with AngularJS and ui-router, we define a state like this: .state('myState', { url: 'some-user-friendly-url' ... }) This allows us to easily specify the URL and name of the state. It simplifies navigation by letting ...

What is preventing me from retrieving a value from a member function or method within a TypeScript class instance?

I am facing an issue with the FileInfo class that implements the IFileInfo interface. This class has an instance member function ext and a function getExt(). Within my component, there is a private method named openTempFolder() which makes an HTTP call to ...

The type 'Observable<Student[]>' is lacking important properties such as id, first_name, last_name, English, and more within the type 'Student'

I have developed two components (table and form) and I am working on transferring data from the form component to the table component when editing. The code that I have written is currently throwing an error. However, when I check the console using console ...

Can we determine the data type of a value within a class instance by utilizing a function to retrieve it?

Is it feasible to create a function that maintains typing and functions in the same way as this: class Example { someNumber:number = 1; someString:string = "test"; } const example = new Example(); const value = example.someNumber; // typ ...

Creating a numeric sequence based on the date of a corresponding transaction - a step-by-step guide

INTRO I built an e-commerce app with TypeScript and Sequelize ORM. In the app, I have a table that generates sequential invoice numbers based on the current day. CREATE TABLE `dm_generate_trx` ( `id` int NOT NULL AUTO_INCREMENT, `date` date NOT NULL, ...

Error: The OOP class value for translateX in the Web Animation API is returning as undefined

I'm currently working on a basic animation project using JavaScript. I have utilized the Animation class from the Web Animation API. My goal is to create multiple instances of this class in order to animate different elements with varying values and r ...

Create dynamic modals in ReactJS that appear when a row is clicked

Engaged in a project for an undisclosed entity where patient data is retrieved from their API and displayed as modal on the page. Clicking on a modal reveals more threat information in another modal. The objective is for these modals to render based on a c ...

What is the method for extracting an Ionic image URL from an image that has been uploaded to Firebase?

I'm currently working on uploading an image from a phone in Ionic using Cordova: async takePhoto(sourceType: number) { try { const options: CameraOptions = { quality: 50, targetHeight: 100, targetWidth ...

Guide to implementing a Page Object Model for improved debugging of Protractor tests

Introduction I am on a mission to streamline my e2e testing code using the Page Object Model for easier maintenance and debugging. My Approach When embarking on creating end-to-end tests with Protractor, I follow these steps to implement the Page Object ...

Incorporate Angular frontend into current website or project

I've successfully built a website using bootstrap, but now I'm looking to integrate Angular in order to transform it into a single page application. The goal is that when a user clicks on a link, only the necessary content will be loaded from the ...

Struggling to configure Connected React Router correctly

As I work on updating my React, Redux, and Router versions to incorporate connected-react-router, I've encountered an issue with the root reducer and store creation process. The previous functioning reducer code looked like this: const appReducer = ...

Unable to access property 'create' which is undefined

On my Ionic3 page, I am trying to trigger a modal open from within a click event function. export class HomePage { .... .... .... loadPos() { var randomLocations = Microsoft.Maps.TestDataGenerator.getLocations(5, this.map.getBounds()); ...

The variable <variable> is not meeting the 'never' constraint. Error code: ts(2344)

Currently, I am attempting to utilize Supabase alongside TypeScript. However, I encounter an error when trying to use functions like insert(), update(), upsert(), etc. Specifically, the issue arises when declaring the object I want to declare: "Type & ...