The service's use of the `next()` method from the RxJs BehaviorSubject

My current strategy involves refreshing the Details page after a new record is added, as well as after updating a record.

DataRefreshService

export class DataRefreshService {
    private dataTracker = new BehaviorSubject<any>();

    getData(): Observable<any> {
        return this.dataTracker.asObservable();
    }

    setData(param: any): void {
        this.dataTracker.next(param);
    }
}

CreateComponent:

export class CreateComponent implements OnInit {

    constructor(private dataRefreshService: DataRefreshService) { }

    create(param: any): void {
        //other actions related to record creation

        this.dataRefreshService.setData(param);
    }
}

DetailsComponent:

export class DetailsComponent implements OnInit {

    subscription;

    constructor(private dataRefreshService: DataRefreshService) { }

    ngOnInit() {
        this.subscription = this.dataRefreshService.getData().subscribe((param: any) => {
            this.updateRecord(param);
        );
    }

    updateRecord(param) {
        this.record = param; //updating record with new data from service
    }

    ngOnDestroy(): void {
        this.subscription.unsubscribe();
    }
}

While my approach works effectively, I have some concerns:

1) Given that I call

this.dataRefreshService.setData(param);
in both the create() and update() methods, should I consider moving this operation to the service level instead of the component level?

2) Is there anything problematic about invoking the next() method in the CreateComponent as shown above?

Answer №1

Your design seems solid with the use of BehaviourSubject (at least from my perspective).

One suggestion I would make is to consider using BehaviourSubject in a singleton service (which may not be apparent in your current setup)

What if I were to call the setEvent() method within the create() function of another service where CRUD operations are defined?

If I understand your question correctly, the answer is NO.

It's generally not advisable to call one service method from another, so it's best to keep things simple. In real-world projects, after CRUD operations have been completed, data refreshing can typically be handled by the component itself using service methods (as opposed to within the service).

I currently call next() via the setEvent() method after each CRUD operation. Is this a good approach or is there a better way, such as calling next() directly within the service itself as mentioned in the initial question?

Yes, the approach you're taking is a good one.

Answer №2

In my opinion, the approach you are taking is completely legitimate. One suggestion could be to implement restriction rules, as you have mentioned, that only allow calling setEvent from the service layer. This would enhance the component's single responsibility. However, the effectiveness of this depends on the scale and duration of your project. When starting a new project, I would definitely follow the same path as you did!

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

Renew your subscription to an observable using rx-angular

Looking to implement angular-rx for a straightforward refresh button feature. When the user clicks the refresh button, the results should be reloaded. In case the user rapidly clicks the refresh button 100 times in one second, only the latest results shoul ...

There seems to be an issue with the Angular2 program, as it doesn't seem to be running properly

Today marks my first venture into using Angular2 with TypeScript. Unfortunately, I encountered an error while attempting to run my Angular2 program using npm start. > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5e3f303 ...

Creating an Angular 2 project with DevExtreme in Visual Studio 2017/2015: A step-by-step guide

I would appreciate some guidance on setting up an Angular 2 project with DevExtreme control using Visual Studio 2017/2015. Specifically, I am interested in utilizing the control demonstrated at . Your assistance would be greatly appreciated. ...

Dividing a TypeScript NPM package into separate files while keeping internal components secure

I have developed an NPM package using TypeScript specifically for Node.js applications. The challenge I am facing is that my classes contain internal methods that should not be accessible outside of the package, yet I can't mark them as private since ...

How can the creation of directories for services be avoided in angular-cli?

For those of us using angular-cli, starting from version 1.4, they made the decision to create separate directories not just for components (which is understandable) but also for services that only consist of 2 files: the service file and the test file. ...

Exploring TypeScript's reluctance to automatically infer value types and strategies for overcoming this behavior

I have been working on implementing a type-safe router in TypeScript and I am facing challenges with inferring types. export interface Route<Args> { match(path: string): Args | void; build(args: Args): string; } export type Routes<State> ...

Having difficulty accessing the value of a table td element in HTML using a jQuery selector

When creating a table, I utilize ng-repeat to generate table rows. Whenever the dropdown changes, a function is triggered which applies certain conditions. Based on these conditions, an object is added to an array that is bound to a scope variable. Here i ...

Java running on a Tomcat server is failing to serve Angular transpiled files

After configuring my Tomcat server to run through IntelliJ Ultimate Edition, I encountered an issue when trying to load my Angular webpages transpiled into .js files. Even though the files are located within the webapp folder, the server kept giving me a " ...

Removing a header in angular based on a specific name - a step-by-step guide!

Within my application, I am making multiple HTTP requests that all require an authentication header with an access token (along with other header values). I have defined a header variable of type HttpHeaders (refer to code#1) to be used as follows: this.ht ...

Encountering error message "Module not found '@angular/compiler-cli/ngcc'" while attempting to run "ng serve" for my application

Encountering an error while trying to run my app, I have attempted various solutions available online. These include uninstalling and reinstalling angular/cli, verifying the correct version in package.json (ensuring it is "@angular/cli" and not "@angular-c ...

What is the process for utilizing datePipe in an Angular component?

How can I implement DatePipe in my Angular component? This is the code snippet that I am currently using. for (let i = 0; i < this.days.length; i++) { this.storeStart(this.days[i], null, null, null); } I have stored weekdays (Monday to Frid ...

Module 'serviceAccountKey.json' could not be located

I'm encountering an issue while trying to incorporate Firebase Functions into my project. The problem lies in importing the service account key from my project. Here is a snippet of my code: import * as admin from 'firebase-admin'; var ser ...

Displaying ASP.Net Core Application on local IIS - Unable to locate content

I started a new project in Visual Studio Code by running the following command: dotnet new angular --use-local-db Afterwards, I upgraded Angular from version 8 to 10 and completed the project. To test it, I used dotnet watch run Everything was running ...

Automating email testing for Azure Graph-built applications: A step-by-step guide

I am exploring options to streamline the email testing process for an application developed with Azure Graph integration. Currently, I am leveraging playwright and typescript for other testing purposes within the application. One of the key functionaliti ...

The separator falls short of spanning the entire width of the page

For some reason, I can't seem to make the divider extend to the full length of the page. <TableRow> <TableCell className={classes.tableCell} colSpan={6}> <Box display="grid" gridTemplateColumn ...

Encountering compilation error while trying to run ng serve command

enter code hereERROR in ./node_modules/ng-otp-input/fesm2015/ng-otp-input.js 32:149-167 "export 'ɵɵFactoryTarget' (imported as 'i0') was not found in '@angular/core' ERROR in ./node_modu` { "name": "jugnoo-user-web ...

Struggling with the error message "Type 'ChangeEvent<unknown>' is not assignable to type 'ChangeEvent<MouseEvent>'" while working with React and TypeScript? Here's how you can tackle this issue

Within the App.tsx file, I encountered an issue with the Material UI Pagination component where it was throwing an error related to type mismatch. The error message stated: Argument of type 'ChangeEvent' is not assignable to parameter of type &ap ...

Encountering a problem when utilizing window.ethereum in Next Js paired with ether JS

Experiencing some difficulties while utilizing the window.ethereum in the latest version of NextJs. Everything was functioning smoothly with NextJs 12, but after upgrading to NextJs 13, this error started popping up. Are there any alternative solutions ava ...

Having difficulty configuring default tab based on conditions in a kendo-tabstrip

I have a situation in my angular project where I need to implement three controls on a page, each of which should be able to open a popup independently. This popup consists of three tabs, and I want to set a default tab for each control. To open the popup, ...

Angular: Creating an input field with preset value that is immutable

I am a beginner with angular and I have been working on this code snippet: <mat-form-field appearance="outline" class="col-30" id="mat-identifier"> <mat-label> {{'columns.dashboard.identifier' | ...