synchronize the exchange of information and events between two components

Just joined this platform and diving into Angular 7 coding, but already facing an issue.
I've set up two components along with a service. The data is fetched by the service upon clicking a button in the searchbar component, and I aim to display it in the search-res view. The service has to extract data from the searchbar component.

Check out the service code below:

import { Injectable } from '@angular/core';
import { HttpClient } from '@common/http'
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class DataService {

  constructor(private http:HttpClient) { }

  getData( input:string ):Observable<any>
  {
   return this.http.get<any>('https://newsapi.org/v2/everything?q='+input+'&apiKey=b9d34afdf37948cda401c3dc0afe1189')
  }

}

I'm uncertain about how to proceed in these components:

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';

@Component({
  selector: 'app-searchbar',
  templateUrl: './searchbar.component.html',
  styleUrls: ['./searchbar.component.css']
})
export class SearchbarComponent implements OnInit {
  public inData : string ;  

  constructor(private data : DataService) { }

  ngOnInit() {
  }

}

search-res component

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';

@Component({
  selector: 'app-search-res',
  templateUrl: './search-res.component.html',
  styleUrls: ['./search-res.component.css']
})
export class SearchResComponent implements OnInit {

  constructor(private data: DataService) { }

  ngOnInit() {
  }

}

Any assistance would be greatly appreciated!

Answer №1

Welcome to the coding world!

When it comes to coding, there are always multiple paths you can take. The relationship between the SearchbarComponent and SearchResComponent may not be clear at first glance.

Subscribing from both components

This method is straightforward and doesn't require any direct connection between the two components. However, it may result in receiving the data twice. It's a good starting point for a prototype but might not be ideal for a production environment.

Subscribing in one component and passing data to the other

If one component is a child of the other, you can pass data using Input properties.

Building a data cache

You can retrieve the data once and store it in a service, manage a simple property in your DataService, or even create an HttpInterceptor to handle caching. However, managing the cache can become complex as you need to invalidate it when data changes.

Using a state management library

State management libraries like NgRx can handle caching data and provide it to any component that needs it. While great for production applications, they may be daunting for new Angular developers due to their use of RxJS.

Each option has its complexities and advantages. Let me know if you're interested in exploring any specific choice further, and I can offer more guidance.

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

I want to make my code available as an npm library on GitHub, but when users install it, I want them to only get

When pushing the code to GitHub, I also need to include the dist folder. However, when running the command npm i <github-url>, I want the node_modules files to be downloaded and placed inside the dist folder. ...

Unable to assign a value to an undefined property in TypeScript

I need to store data in an object and then add it to another object let globalSamples = {} as any; let sample = { } as ISamplesDetail []; sample = []; for (let i = 0 ; i<this.prelevementLingette.samplesDetail.length; i++) { sample [i].id= thi ...

Strategies for Implementing Responsive Design in Angular and Bootstrap Shopping Cart Apps to Deliver Custom Views on Mobile and Desktop Devices

Our shopping cart application utilizes Angular and Bootstrap. We are in need of routing different pages for mobile and desktop screens. Specifically, we want the /cart route to display a different page on mobile devices compared to desktops, taking into ...

When I pass an array of objects to Firefox (using TypeScript) and retrieve the data, I find that I am unable to retrieve it in the form of an array of objects

When it comes to saving and retrieving data from a Firebase database, I seem to be encountering an issue where the type of data retrieved does not match what I am expecting. Let me break down what I am doing and the problem I am facing: Saving data To sa ...

Developing a MEAN-based calendar application that is constantly monitoring for updates

I am considering developing a calendar web app to enhance my web development skills. After carefully planning the structure and technologies, I have decided to use the MEAN stack. However, I have encountered a challenge: I want the angular front-end to a ...

Setting up Typescript classes that inherit from one another with diverse properties for each subclass

I'm fairly new to Typescript and currently grappling with how to effectively manage class inheritance when base classes have distinct properties. Essentially, I have a base class where I aim to define shared functionality and a series of subclasses w ...

Failure to nest interfaces in Angular when mapping JSON responses

After calling my ASP.NET Core Web API, the JSON response appears as: [ { "driver": { "firstName": "TEST", "lastName": "LAST", "assignedRoute": "O_ROUTE" } }, { "driver": { "firstName": "First", "lastName": " ...

When making a GET request with Angular and NodeJS that includes parameters, only the response object is returned without any associated

Let's say I have a URL like 'localhost:3000/verify/a5d5sd', which I send to a user via email. When the user clicks on this link, I use the parameter (a5d5sd) in the link to check some conditions on the server and in my MongoDB database. The ...

Unable to access any pages using the angular-cli http-server for deployment

When I run my project using 'ng serve', everything works fine. However, when I deploy it on a server using 'http-server ./dist', none of the pages can be accessed and an error message is displayed: host:~/morange/project$ http-server . ...

How can I utilize Angular and TypeScript to loop through the innerHTML property binding effectively?

I'm currently working on using ngFor to display the binding details of the innerHtml property. <ul> <li *ngFor="let n of NotificationData"> {{n.NotificationID}} <label [innerHtml]="n.NotificationText | StyleHtml&quo ...

The error message displayed by Create React App states: "You cannot utilize JSX without the '--jsx' flag."

I need help with overcoming this particular issue in a TypeScript based React application: Encountering an error stating "Cannot use JSX unless the '--jsx' flag is provided" ...

Is there a way to retrieve the initial item of a JSON array from an HTML document using Angular 2?

Within the src/assets/ directory, I have a json file called product.json with the following structure: [ { "images": "http://openclipart.org/image/300px/svg_to_png/26215/Anonymous_Leaf_Rake.png", "textBox": "empty", "comments": "empty" }, { "i ...

unable to locate the nested routes in the folder for remix

Hey there, I've been using the remix to create a basic page and I'm trying to organize the routes using folders. Here is my project directory: - app/ - root.tsx - examples/ - route.tsx - child1/ - account.tsx In the examples di ...

What could be causing my Bootstrap accordion to not expand or collapse within my Angular application?

Struggling with my Accordion Angular component that utilizes Bootstrap - the collapsing and expanding feature isn't functioning properly. I've simply copied the bootstrap code into my accordion.component.html. <div class="accordion accord ...

Could the repeated utilization of BehaviorSubject within Angular services indicate a cause for concern?

While developing an Angular application, I've noticed a recurring pattern in my code structure: @Injectable(...) export class WidgetRegsitryService { private readonly _widgets: BehaviorSubject<Widget[]> = new BehaviorSubject([]); public get ...

What are the steps to set up NextJS 12.2 with SWC, Jest, Eslint, and Typescript for optimal configuration?

Having trouble resolving an error with Next/Babel in Jest files while using VSCode. Any suggestions on how to fix this? I am currently working with NextJS and SWC, and I have "extends": "next" set in my .eslintrc file. Error message: Parsing error - Can ...

Discovering a solution to extract a value from an Array of objects without explicitly referencing the key has proven to be quite challenging, as my extensive online research has failed to yield any similar or closely related problems

So I had this specific constant value const uniqueObjArr = [ { asdfgfjhjkl:"example 123" }, { qwertyuiop:"example 456" }, { zxcvbnmqwerty:"example 678" }, ] I aim to retrieve the ...

Trying to toggle between two Angular components within the app component using a pair of buttons

Currently, I am developing an application that requires two buttons to display different nested apps. Unfortunately, I am unable to use angular routing for this particular design. These two buttons will be placed within the app.component. When Button A i ...

Pausing repetitive HTTP requests in an Angular 6 project within a do while loop

While waiting for the completion of one API call, I am recursively consuming an external API. The http calls are being made using import {HttpClient} from '@angular/common/http' As a newcomer to the framework, there may be something wrong in the ...

The Angular 2.0 HTTP post request encountered an error when trying to respond with a status of 200 Ok for a null

I'm currently attempting to post data using http in Angular 2. I have added an http call with the corresponding API, and when I click the button, it should send data to my database. However, an error is showing up in the console. XMLHttpRequest canno ...