Invoking Component Function via Service

I am in the process of developing a file upload feature for my application. Once the files are successfully uploaded, I want to clear the list of uploaded files. To achieve this, I have created the following function in the file uploader component:

  clearFileList(){
    this.uploadedFiles=[]
  }

Now, I would like to invoke this function from a service so that I can reuse it in other components. How can I accomplish this?

Answer №1

Using a service to call a component function may not be the best practice. I recommend a different approach where the service contains a public subject that the component can subscribe to:

class DataService {
  public dataStream$ = new Subject<any>();

  sendData() {
    this.dataStream$.next(...);
  }

}

class DisplayComponent {
  constructor(private dataService: DataService) {}

  ngOnInit() {
    this.dataService.dataStream$.subscribe(data => {
      this.displayData(data);
    }
  }

  displayData(data) {
    // do something with the data
  }

}

The service can trigger the sendData method, which will then invoke the component's method.

And don't forget to unsubscribe when necessary.

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

Updating a unique field with the same value causes a failure in the TypeORM update process

I am working with a service model in TypeORM, where I have a field called service_name that must be unique. However, when I attempt to update the table with the same value for service_name, it triggers a unique constraint violation error. I'm puzzled ...

What is the process for creating a PickByValue data type?

The TypeScript language comes with a built-in Pick type, which is defined as follows: type Pick<T, K extends keyof T> = { [P in K]: T[P]; }; If you were to create a custom PickByValue type, how would you implement it to achieve the following func ...

How can I pass custom QueryParams to Router's NavigationExtras in Angular and create a personalized navigation experience?

I am currently working on implementing data filtering functionality in my Angular application. The concept is fairly simple - the user selects filters from dropdown menus and then clicks a button to add key-value pairs of filters to the URL route. There a ...

What is the best way to execute an Nx executor function using Node.js?

Can a customized Nx executor function be executed after the app image is built? This is the approach I am taking: "migrate-up": { "executor": "@nx-mongo-migrate/mongo-migrate:up", "options": { &q ...

Excluding a Navbar in Angular 2: What is the best way to hide the navbar on a

Within app.component.html, I always incorporate the navbar on every page with the following code: <app-navbar></app-navbar> Is there a way to omit the navbar from a specific page? ...

The information that is visible in the console is failing to appear in the view

My issue revolves around retrieving data from Firestore. While the console displays the data correctly, my view ends up showing empty cards. Consider the following HTML code: <ion-grid> <ion-row> <ion-col size="12" > ...

Having difficulty navigating to a different page in Angular 4

I'm currently attempting to transition from a home page (localhost.com) to another page (localhost.com/listing). Although the app compiles correctly, I encounter an issue where nothing changes when I try to navigate to the new page. My approach has m ...

Even after setting [attr.disabled]="false" in Angular, the Textarea still remains disabled

I am currently utilizing ngModel for a textarea, and I would like to be able to enable and disable the textarea based on a certain condition. Even though I have bound it correctly and the value is changing to [attr.disabled]="false", the textarea remains d ...

The distinctUntilChanged function encounters an issue when no comparison function is given

considering the following code: /** * Generating a stream of car objects from an array. */ from([ { name: 'Porsche', model: '911' }, { name: 'Porsche', model: '911' }, { name: 'Ferrari', model: &apo ...

Having difficulty utilizing defineProps in TypeScript

For some time now, I've been utilizing withDefaults and defineProps. Unfortunately, this setup has recently started failing, leaving me puzzled as to why! Here's a simple SFC example: <script setup lang = "ts"> const props ...

The file could not be located on the server during the project build and upload process

Presently, I'm engrossed in a project involving Angular 9 and ASP Core 3. You can find the website at: Nevertheless, encountering an error when trying to access this URL: http://mag-testcpl.astromap.ir/assets/vendors/global/toastr.css The culprit ...

Angular4: The dragstart event is being triggered as a result of the mousedown event

My div contains a mousedown event for the parent element and a dragstart event specific to that div. However, I am facing an issue where the dragstart event is not being triggered when I try to drag the div. I attempted to use event.stoppropagation() with ...

CORS policy is preventing a patch request in loopback 4 from going through

Whenever I attempt to send a patch request to my API using Loopback 4, I encounter an error. All other requests work perfectly fine except for the patch request. The error message states: Access to XMLHttpRequest at 'api url' from origin ' ...

Storing Json data in a variable within Angular 2: a step-by-step guide

https://i.sstatic.net/2QjkJ.png Within the params.value object, there are 3 arrays containing names that I need to extract and store in a variable. I attempted to use a ForEach loop for this purpose, but encountered an issue. Can you spot what's wron ...

What is the process for eliminating the perplexing "default" attribute that has been inserted into JSON?

I recently came across the jsondata.json file: { "name": "John", "age": 30, "car": "ferrari" } Located in the same directory is a typescript file called main.ts where I simply output the json data using console.log import * as j from '. ...

Linking to a file within an npm package

Is it possible to reference local files within an npm package? Will these references still work correctly when the package is installed by a different consumer? For example, let's say I have developed an npm package for Angular which includes some HTM ...

Communication between related components in Angular involving siblings

I am currently working in Angular 4 with sibling components, where there are no parent-child relationships, only siblings. One of the siblings is able to successfully retrieve data, particularly the ID from the URL using the code snippet below: public ge ...

Iterating through an array and setting variables according to asynchronous code

I have created a function to loop through an array, call a promise, and update a variable based on the result. The code seems to be functioning correctly, but I am wondering if there is a more optimal way to write it. Any suggestions are appreciated. Tha ...

What is the best way to locate and access a JSON file that is relative to the module I am currently working

I am in the process of creating a package named PackageA, which includes a function called parseJson. This function is designed to accept a file path pointing to a JSON file that needs to be parsed. Now, in another package - PackageB, I would like to invok ...

Error TS2322: Cannot assign type 'Foo | Bar' to type 'Foo & Bar'

I am attempting to save an item in an object using the object key as the discriminator for the type. Refer to the edit below. Below is a simple example: type Foo = { id: 'foo' } type Bar = { id: 'bar' } type Container = { foo ...