Ways to transmit information or notifications from a service to a component

Currently, I am utilizing Angular 6 and have the upload file control on three different screens (three various components). Each of these screens calls the same method UploadFile(). The main issue arises when I need to make any changes to this method, as I have to update it in all three places. To tackle this problem, I have decided to create a service (non-shared) containing the method UploadFile(), which will allow me to make changes in one place only and be called by all three screens. However, I am facing a challenge regarding how to return alert messages and both success and failure responses from another service within this service back to the components.


@Injectable({
  providedIn: 'root'
})

export class MyFileUploader {

  fileuploadList: EventUpload[];
  eventId: Number;
  constructor(private dateFormatHelper: DateFormatHelper, private manageService: ManageService) {
  }

public UploadFile(event) {
     const fileList: FileList = event.target.files;
     if (fileList.length > 0) {
         const file: File = fileList[0];
         const extension = fileList[0].name.split('.').pop();

        if (this.fileuploadList.find( f => f.fileName === file.name)) {
           alert('Duplicate file identified!');
           return;
        }
         const formData: FormData = new FormData();
         const params = Object.assign({}, {
              Id: 0,
             F ileName: file.name,
              FilePath: 'XXXXXX', 

         });
         formData.append('uploadFile', file, params.FileName);
         formData.append('data', JSON.stringify(params));
         this.manageService.uploadAttachments(formData).subscribe (resp => {
           if (resp === -1 ) {
             alert('Error occured while uploading the attachment');
             return;
            } else {
              this.fileuploadList.push (new DataUpload (0, params.FileName, 
           params.CreatedBy,));
             }
         },
       (error) => {
         console.log('POST ERROR in method uploadAttachments: ' + error.error);
       }
       );
     }
 }
}

Answer №1

If you create a method called UploadFile, it has the ability to return a Subject. Here is an example:

public UploadFile(event) {
 const uploadSubject: Subject<any> = new Subject();
 const fileList: FileList = event.target.files;

To import, do the following:

import { Subject } from 'rxjs';

You can use it as shown below:

    if (this.fileuploadList.find( f => f.fileName === file.name)) {
       alert('Duplicate file identified!');
       uploadSubject.next('Duplicate');
       uploadSubject.complete();
    }

When calling this method from another part of your code:

this.myFileUploaderService.UploadFile(event)
 .subscribe(
   (response) => console.log(response), 
   (error) => console.error(error),
   () => console.log('completed')
)

Whenever you call the UploadFile method, you can subscribe to the Subject to receive information from the Service.

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

Content from PHP's unlink() function continues to persistently display

I run an Angular front end along with a PHP back end for my website. I utilize PHP's unlink function to remove specific images from Angular's assets folder: $fileToDelete = "../src/assets/images/".$name; unlink($fileToDelete) or die("Error delet ...

Incorporate an HTML span element with an onclick function bound in Angular framework

Is there a way to incorporate different icons by adding a span based on a flag, with an onclick event that triggers an internal function defined in the component ts? testfunc(){ console.log("it works") } flagToIcon(flag: boolean) { switch ( ...

Using Partial function input in TypeScript

I am in need of a function that can accept partial input. The function includes a variable called style, which should only have values of outline or fill, like so: export type TrafficSignalStyle = 'outline' | 'fill' let style: TrafficSi ...

The lazy loading feature in Angular 12 is not functioning correctly for path modules

My application has a jobs module with various components, and I'm trying to lazy load it. However, I've encountered an issue where accessing the module through the full path http://localhost:4200/job/artist doesn't work, but accessing it thr ...

Validate multiple email addresses in a single input field, such as adding multiple recipients to the CC field in an email form using

Currently using Angular2 and primeng to create a basic email form with the following input fields: To: Cc: Message: Here is an excerpt of the code from my component class: constructor(private fb: FormBuilder) { this.createForm(); } createForm ...

Can an attribute be assigned to an Angular host element without specifying a value?

Exploring the concept of host binding on the input element's readonly attribute, aiming to add the attribute without assigning any value. Even though HTML specifications state that assigning a value may not make a difference as long as the attribute i ...

Using source maps with Typescript in Webpack (source maps not visible while using webpack-dev-server)

I am currently experimenting with Typescript in combination with Webpack, utilizing the 'awesome-typescript-loader' plugin. However, I am encountering an issue where the source maps are not displaying in the browser when running webpack-dev-serve ...

Stop Angular (click) binding from occurring when the variable is considered 'undefined'

Currently, I am enhancing a custom Angular component by adding callbacks using the standard Angular method, like so: (click)="data.callback ? data.callback() : undefined" This approach works smoothly; when no callback is specified, Angular handl ...

Angular Material Datepicker with Selectable Date Range

In my project using Angular 8, I needed to incorporate a datepicker with highlighted date ranges. I came across an example image here: view image. I tried to find a suitable package like the one mentioned in this link: https://www.npmjs.co ...

Styling child elements in Angular using css from its parent element

I have a question: Regarding the structure below <component-parent> <first-child> <second-child> <third-child></third-child> </second-child> </first-child> </component-parent> Now I want t ...

What is the appropriate method to utilize the scrollable feature in Tab View?

Currently, I am incorporating p-tabview and trying to enable the scrollable property as indicated on the primeng website: https://www.primefaces.org/primeng/showcase/#/tabview However, an error is showing up that says Can't bind to 'scrollable&a ...

Understanding the operational aspects of Typescript's target and lib settings

When the tsconfig.json file is configured like this: "target": "es5", "lib": [ "es6", "dom", "es2017" ] It appears that es2017 features are not being converted to es5. For example, code like the following will fail in IE11: var foo = [1, 2, 3].includes( ...

Is there a way to adjust the StatusBar color or make it transparent on Android when working with NativeScript and Angular?

I am having trouble changing the StatusBar color in my NativeScript with Angular project. It currently appears as translucent black, darkening the background behind it. I want to either make it transparent or match the background color of the page. What I ...

Translate Firestore value updates into a TypeScript object

Here are the interfaces I'm working with: interface Item { data: string } interface Test { item: Item url: string } In Firestore, my data is stored in the following format: Collection Tests id: { item: { data: " ...

Encountering difficulties retrieving information from an API using Angular

I am encountering an issue while trying to retrieve data from an API. When I use console.log() to view the data, it shows up in the console without any problem. However, when I attempt to display this data in a table, I keep receiving the error message: ER ...

search for a specific value within a nested subfield of an asterisk star field in Firestore

Here is the data I have: { root: { _rEG: { fen: 'value' }, _AS: { fen: 'value' }, _BSSA: { fen: 'value' } } } I would like to query using where('root.*.fen', '==', 'value'). ...

Tips for sending just the updated section of the form

I am working with a form group where I map the values from the form to an object type in order to make a request to edit the item. This is my form structure: public companyForm = new FormGroup( { generalInfo: new FormGroup({ name: new ...

Transitions fail to appear correctly when the page first loads

I need to fill a gauge meter based on a variable sent to the html file. To achieve this, I have initially set the value to zero: transform:rotate(.0turn); transition: all 1.3s ease-in-out; However, when the HTML is first loaded or refreshed (with F5 ...

Utilizing custom types in React with TypeScript and Prop-Types

Currently, I am working with a string type literal that looks like this: type MyType = 'str1' | 'str2' | 'str3'. I need one of my props to only accept this specific type, but I'm struggling to specify this in PropTypes. ...

The pagination in React using React Query will only trigger a re-render when the window is in

Currently, I am utilizing React-Query with React and have encountered an issue with pagination. The component only renders when the window gains focus. This behavior is demonstrated in the video link below, The video showcases how the component re-renders ...