Learn the steps to refresh a component in Angular 5

src/shared.service.ts

    public _testData:any;

      set testData(value:any) {
        this._testData = value
      }

      get testData():any {
        return this._testData;
      } 

src/header.component.ts

 private postValues() {
    this._PartService.PostDataValues(this.search).subscribe(
      result => {
         this.sharedService._testData
        })
  }

  onSearch() {
       this.postValues()
   }

src/home.component.ts

private downloadRecentSearches() {
   this.recentSearchService.download().subscribe(
    searches => {
      this.resultData = searches;
      this.originalSearches = this.resultData.data;
      this.sharedService._testData = this.originalSearches
      this.onSelectItem()
    })
  }

The code snippet above involves assigning the result to "this.sharedService._testData". In the header component, upon clicking search, the new search result is saved and needs to be updated in the home component. However, there is uncertainty regarding how to navigate back to the home component to retrieve the latest search results.

Answer №1

Utilizing angular's EventEmitter can facilitate component communication. Upon triggering the onsearch event, you have the ability to dispatch an event to other components along with the user-inputted value stored in this.search. Subsequently, within your home component.ts file, you can listen for the emitted event and validate whether it returns any data (such as the search query). If a valid value is returned, you can invoke the downloadRecentSearches() function and pass in the retrieved value.

To delve deeper into component interaction within Angular, refer to the documentation available here.

For example:

shared.service.ts

import { Output, EventEmitter } from '@angular/core';

@Output() search: EventEmitter<string> = new EventEmitter();

searchChanged(value) {
   this.search.emit(value);
}

search.component.ts

import { HostListener } from '@angular/core';

@HostListener('change')
onSearch() {
   this.sharedService.searchChanged(this.search)
}

home.component.ts

constructor() {
  this.eventListener();
}

eventListener() {
   this.sharedService.search.subscribe((searchValue) => {
       console.log(searchValue) // value of the inputted by user
       // do your logic here
   })
}

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

Can TypeScript support passing named rest arguments within the type declaration?

Using Tuple types in TypeScript enables us to create typesafe rest arguments: type Params = [string,number,string] const fn = (...args: Params) => null // Type is (args_0: string, args_1: number, args_2: string) => null Is there a method to assign ...

Accessing and sending only the body part of an HTTP response in Angular 7 test cases: A comprehensive guide

Currently, I am working on creating unit test cases in Angular 7 for a Component that utilizes an asynchronous service. This is the content of my component file: submitLoginForm() { if (this.loginForm.valid) { // send a http request to save t ...

Using TypeScript, pass an image as a prop in a Styled Component

I am facing an issue with the code below that is supposed to display the "NoBillsLaptopPNG.src" image on the screen, but for some reason, the image is not showing up. The images are being imported correctly, so I'm unsure why the image is not appeari ...

NPM packages: Providing a comprehensive assets and images delivery solution package

After creating a custom (angular2) npm package and uploading it to my personal registry, I encountered an issue with delivering the icons along with the component. The component should display an icon by using the following template: <span [class]="& ...

Steps to deactivate an angular material component on version 2.0.0-beta.5

Recent updates have led to an error in my code: Error at /Users/asaylor/Desktop/RevenueIQ/website/aot/node_modules/@angular/material/typings/index.ngfactory.ts:4236:30: Property 'disabled' does not exist on type 'MdCheckbox' I am enc ...

typescript loop with a callback function executed at the conclusion

I am struggling with this code and it's driving me crazy. addUpSpecificDaysOfWeek(daysInMonth: any, callbackFunction: any){ var data = []; var that = this; daysMonth.forEach(function(day){ that.statsService.fetchData(that.userid, d ...

Is there a way to showcase the data of each table row within the tr tag in an Angular 8 application?

I have been developing an application using Angular 8. The employee-list component is responsible for presenting data in a table format. Within the employee-list.component.ts file, I have defined: import { Component } from '@angular/core'; impo ...

Using multiple flatMap responses within the map operator across various functions: a guide

I've been working on a solution to connect multiple operations within a map function that follows the flatMap operator. Here's how it currently functions: flatMap( someResponse => combineLatest([ this.locator.function(someResponse, var ...

Is it necessary for me to set up @types/node? It appears that VSCode comes with it pre-installed

Many individuals have been adding @types/node to their development dependencies. Yet, if you were to open a blank folder in VSCode and create an empty JavaScript file, then input: const fs = require('fs'); // <= hover it and the type display ...

Avoiding Re-renders in an Angular2 Countdown Component

I am facing an issue with my Angular2 master component that includes multiple child components and a standalone countdown component called "clock". The countdown component updates its label every second, causing unnecessary re-rendering of the master compo ...

Please ensure that the table contains all the records corresponding to the respective days

I am struggling with figuring out how to display a record of classes in my table view. The UX prototype I need to follow is shown https://i.stack.imgur.com/CISYn.png (the days of the week are in Portuguese: horario = time, segunda = Monday, terça = Tuesda ...

Error: Reference to an undeclared variable cannot be accessed. TypeScript, Cordova, iOS platforms

Can anyone offer some advice on what might be the issue? I'm encountering an error while building my Ionic app on the IOS platform, but everything is running smoothly on Android. ReferenceError: Cannot access uninitialized variable. service.ts:31 O ...

Error encountered while implementing onMutate function in React Query for Optimistic Updates

export const usePostApi = () => useMutation(['key'], (data: FormData) => api.postFilesImages({ requestBody: data })); Query Definition const { mutateAsync } = usePostApi(); const {data} = await mutateAsync(formData, { onMutate: ...

Ensuring the safety of generic types in Typescript

Typescript is known for its structured typing, which is a result of the dynamic nature of Javascript. This means that features like generics are not the same as in other languages with nominal type systems. So, how can we enforce type safety with generics, ...

Distinguishing Between TypeScript Interface Function Properties

Could anyone clarify why the assignment to InterfaceA constant is successful while the assignment to InterfaceB constant results in an error? interface InterfaceA { doSomething (data: object): boolean; } interface InterfaceB { doSomething: (data: obje ...

Access the properties of the encapsulated component in Vue 3, allowing for IDE autocomplete support

I have a vue3 component named MyButton which acts as a wrapper for the vuetify v-btn component. I am trying to figure out a way to make MyButton props inherit all of the props that v-btn has and also enable autocomplete feature in IntelliJ or VSCode. Is it ...

The color attribute for the ion-button element is not functioning properly on Android devices in

In my app, it functions correctly when running on iOS, but encounters issues when running on Android. The problem lies in the color attribute not working on buttons and other elements on Android. Removing the attribute makes them visible, but the desired s ...

Manage scss styles consistently across Angular projects with this Angular library designed to

In an effort to streamline my development process, I am looking to consolidate my commonly used styles that are defined in my Angular library. My goal is to easily leverage mixins, functions, variables, and more from my library in future projects. Previou ...

Error: Null is causing an issue and preventing property 'isSkipSelf' from being read in Angular7

While assembling the package for my module, I encountered the following error. TypeError: Cannot read property 'isSkipSelf' of null at ProviderElementContext._getDependency(C:\Users\ravinder\MyProjectName\node_modules\@ ...

Is there a sweet TypeScript class constructor that can take in its own instance as an argument?

I have a scenario where I need to read in instances of Todo from a CSV file. The issue is that Papaparse does not handle dynamic conversion on dates, so I'm currently dropping the object into its own constructor to do the conversion: class Todo { ...