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

How to retrieve the HTTPClient value in Angular?

APIservice.ts public fetchData(owner: any) { return this.http.get(`${this.url}/${owner}`, this.httpOptions).pipe( catchError(e => { throw new Error(e); }) ); } public fetchDataById(id: number, byId:string, owner: any) { ...

Issue with Angular 13 Sass module failing to import specified file during compilation

After upgrading a legacy app to Angular 13, I encountered an issue where certain stylesheets were not being added correctly to the compiled styles.css. This was working fine in Angular 12 with webpack under version 5 and node-sass. I suspect this change i ...

Setting up TypeScript in Jest without the need for webpack

Currently, I'm developing an NPM module using TypeScript without the use of Webpack for compiling scripts. I need some guidance on configuring Jest to properly run tests with TypeScript files. Any recommendations? // test.spec.ts import {calc} from ...

How can Angular developers properly implement token refreshing in their applications?

Recently, I've been struggling with implementing a logic in my code. I have a specific requirement: Whenever there is a signed request (signed - means it has a JWT token for authenticated users) made to the API backend, the API backend may respond w ...

Using Javascript or ES6, you can compare a nested array object with another array of elements and generate a new array based on

I am dealing with a complicated array structure as shown below sectionInfo = [{id: 1, name:'ma'}, {id: 2, name:'na'}, {id: 3, name:'ra'}, {id: 4, name:'ka'}, {id: 5, name:'pa'}]; abc = [{id:'1' ...

Utilizing HTML imports in Typescript for efficient use as TemplateStringLiteral

Recently, I started using TypeScript for the first time and I'm looking to integrate it into my webpack build. Currently, I am working with ts-loader and babel-loader to load TypeScript files while also attempting to include HTML files within the scr ...

Combining portions of objects in Angular2

I want to combine two identical type observables in Angular2 and return an observable of the same type in a function. My goal is to: transform this setup: obs1.subscribe(obs => console.log(obs)) (where I receive): { count: 10, array: <some ...

Expanding TypographyProps and TextFieldProps for enhanced functionality

Currently, I am developing a React component using TypeScript along with Material UI (MUI). The main purpose of this component is to display either an input field or text based on the mode selected. To switch between these modes, the prop mode is utilize ...

Ways to deactivate a text area or mat-form-field

I need assistance with disabling a form field using Angular (4) + Angular Material and Reactive Forms. I have tried searching for syntax options like disabled="true", but haven't found the correct one yet. Can you please provide me with the right synt ...

When using TypeScript with custom components as children in React, the `type` returned by React.Children is a string representing the function

It might sound a bit odd, or maybe I'm completely off track here. While going through some articles and React documentation on getting children and identifying specific child components using React.Component.map(), I ran into an issue with my custom c ...

Include a log out option in the side menu of the ionic2 application

I am working with the sidemenu template to kick off my application. I aim to incorporate a button within the sidemenu that enables users to trigger a modal alert for confirming logout. Below is the code snippet: app.component.ts: import { Component, View ...

Diverse behaviors exhibited by an array of promises

I've developed a function that generates an array of promises: async addDefect(payload) { this.newDefect.setNote(payload.note); this.newDefect.setPriority(payload.priority); const name = await this.storage.get(StorageKeys.NAME); ...

Jest's it.each method is throwing an error: "This expression is not callable. Type 'String' has no call signatures."

I've been attempting to utilize the describe.eachtable feature with TypeScript, but I keep running into an error message stating: "error TS2349: This expression is not callable. Type 'String' has no call signatures." Below is my code snippe ...

Retrieve the status callback function from the service

Can anybody show me how to set up a call-back function between a component and a service? I apologize for my lack of experience with Angular and TypeScript. getDiscount(){ let getDisc = []; getDisc.push({ price: Number(this.commonService.getP ...

Error TS2322: Cannot assign type 'Promise<Hero | undefined>' to type 'Promise<Hero>'

I am currently studying angular4 using the angular tutorial. Here is a function to retrieve a hero from a service: @Injectable() export class HeroService { getHeroes(): Promise<Hero[]> { return new Promise(resolve => { // ...

Combining two streams in RxJS and terminating the merged stream when a particular input is triggered

I am currently developing an Angular application and working on implementing a system where an NGRX effect will make requests to a service. This service will essentially perform two tasks: Firstly, it will check the local cache (sqlite) for the requested ...

Is it Mission Impossible to Combine NodeJs, Restify, SQL Server, TypeScript, and IIS?

Starting a Rest API project using NodeJS with Restify on a Windows environment (local server with IIS and SQLServer) while also using Typescript may seem like a difficult task. Is it an impossible mission? Does anyone have any helpful guides, documentatio ...

When you add the /deep/ selector in an Angular 4 component's CSS, it applies the same style to other components. Looking for a fix?

Note: I am using css with Angular 4, not scss. To clarify further, In my number.component.css file, I have: /deep/ .mat-drawer-content{ height:100vh; } Other component.css files do not have the .mat-drawer-content class, but it is common to all views ...

Creating multiple relationships in TypeORM for entities with private properties

In my node application, I am utilizing the typeorm library for entity mapping. My goal is to establish multiple type relations between entities. While following the documentation, I noticed that the entity properties are marked as public, allowing access f ...

Why should we include the '#' character in jhipster URLs?

Standard Angular applications typically do not include a '#' sign in their URLs. However, in JHipster URLs, the '#' character serves a specific purpose. Can you explain the significance of the '#' symbol in JHipster URLs and h ...