Is it feasible to invoke a method without any arguments on this basic subscription?

  • A BRIEF SUMMARY

Implementing an observable in my code, I strive for maintaining cleanliness and efficiency by utilizing the detectChanges() method to update *ngIf= in the HTML.

  • QUERY

Is there a way to invoke the detectChanges() method within subscribe() function as demonstrated in the following example?

Demonstration (does not work due to overload):


this.subscriptions.add(
  this._hotelEffect
    .getHotel()
    .pipe(map(this.createHotel))
    .subscribe(this._changes.detectChanges)
);

My current workaround:


this.subscriptions.add(
  this._hotelEffect
    .getHotel()
    .pipe(
      map((resp) => {
        this.createHotel(resp);
        this._changes.detectChanges();
      })
    )
    .subscribe()
);

Answer №1

So, is that what you're trying to achieve?

this.subscriptions.add(
  this._hotelEffect
    .getHotel()
    .pipe(map(this.createHotel.bind(this)))
    .subscribe(()=>this._changes.detectChanges())
);

Assuming that this.createHotel can handle the return type of getHotel()

I want to keep my code clean and simple. I need to make a function call.

If this is indeed the case, here's how I would do it:

this._hotelEffect
    .getHotel()
    .subscribe((resp) => {
        this.createHotel(resp);
        this._changes.detectChanges();
      });

Furthermore, since you mentioned managing subscriptions for component destruction, there's a more efficient way using the takeUntil operator

//field 
private onDestroy=new Subject();
ngOnDestroy(){ onDestroy.next();onDestroy.complete()}
   
//and then with ANY observable in the component
this._hotelEffect
    .getHotel()
    .pipe(takeUntil(this.onDestroy))
    .subscribe((resp) => {
        this.createHotel(resp);
        this._changes.detectChanges();
      });

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

Learning how to effectively utilize the tap and map functions in Angular

How can I redirect to a URL received from the backend in my Angular project? public createPaymentMethod(paymentMethodDto: any): Observable<any> { return this.http.post<any>(ConfigService.Configuration.apiUrl + `/payments`, paymentMetho ...

Tips for displaying backend error messages on the frontend

I am facing an issue with returning error messages from the backend to the frontend in my Angular project. The specific requirement is to display an error message when the value of msisdn is not eligible for renewal. Currently, the hardcoded error message ...

Leveraging the power of Bootstrap in combination with Angular 2, integrate both ng-bootstrap and the traditional Bootstrap to enhance

Beginning a fresh Angular 2 Project, I am inclined to incorporate Bootstrap 3 for the user interface. What would be the most advisable approach in this scenario? Is it feasible to blend ng-bootstrap and the original Bootstrap components? I noticed that th ...

Angular's custom reactive form validator fails to function as intended

Struggling to incorporate a customized angular validator to check for date ranges. The validator is functioning correctly and throwing a validation error. However, the issue lies in the fact that nothing is being displayed on the client side - there are n ...

What is the method for generating a data type from an array of strings using TypeScript?

Is there a more efficient way to create a TypeScript type based on an array of strings without duplicating values in an Enum declaration? I am using version 2.6.2 and have a long array of colors that I want to convert into a type. Here is what I envision: ...

The 'prop' property is not found within the 'IntrinsicAttributes & CustomComponentProps' type

I developed a custom module with an interface for props, extending props from a file called /types/SharedProps.d.ts. However, when I import this module into a sample project, the extended props are not included in the component. Below is how the module&apo ...

What is the process for creating route transition animations in Angular RC.5?

Is there a new method for animating routes in transit since routeOnDeactivate has been removed? The official documentation on this topic seems to be unclear. ...

The Angular2 application encountered a 404 file not found error while trying to read a Const from a ts

Recently I started working with angular2 and encountered a problem when trying to access constant values from an external .ts file using the following code: import {apis} from '../constants/apis'; The content of the constants/apis.ts file is as ...

Dealing with TypeScript errors TS2082 and TS2087 when trying to assign an Away3D canvas to a variable

As a beginner with TypeScript, I am in the process of creating an Away3D scene where a canvas element is dynamically generated and needs to be appended to a container. Although the code functions correctly, I am encountering the following compilation erro ...

Basic cordova application that transfers data from one page to another using typescript

Currently, I am developing an Apache Cordova application using TypeScript. However, I am facing a challenge in passing information from one HTML page to another using TypeScript. I would appreciate it if someone could guide me on the steps needed for nav ...

In fact, retrieve the file from an S3 bucket and save it to your local

I've been attempting to retrieve an s3 file from my bucket using this function: async Export() { const myKey = '...key...' const mySecret = '...secret...' AWS.config.update( { accessKeyId: myKey, secretAcces ...

Is there an rxjs operator that includes both on-next and on-error callbacks?

Is there a similar function to promise.then(onNextCallback,onErrorCallback) in rxjs that I can use? I've already tried alternatives like pipe(concatMap(),catchError) but they are not what I am looking for. ...

I require all of this to be brought back as one complete entity. If, for instance, the object is given the value 10/26, it should be interpreted as part of the input

I am facing an issue with my Angular + .NET Application where the search method is not recognizing a specific ConsumerUnit when the input includes a / character. Currently, if I input something like 10/2689123, the application treats the / as part of the ...

Error when using ES6 modules in ts-jest

I keep running into an 'unexpected token' error whenever I run my tests using ts-jest. To show you exactly what's going on, I've created a small repo with all of my current configurations available here: https://github.com/ramoneguru/t ...

When incorporating an array as a type in Typescript, leverage the keyof keyword for improved

I am facing a situation where I have multiple interfaces. These are: interface ColDef<Entity, Field extends keyof Entity> { field: Field; valueGetter(value: Entity[Field], entity: Entity): any } interface Options<Entity> { colDefs ...

Steps for including a component in a loop using Angular 6

I'm working on a component that contains two input fields. The goal is to have a row pop up every time the user clicks on the add button, with all the inputs eventually being collected in an array of objects. For example, the component template looks ...

The error message 'tagName' is not a valid property for type ChildNode in Typescript

When I loop over childNodes from a parent node, I encounter an issue while trying to access the tagName of the child nodes. The error message states that tagName does not exist on type ChildNode. const contentParsed = new DOMParser().parseFromString(conte ...

"Creating a Typescript function that guarantees a non-null and non-undefined return

Currently, I am working on developing a function that is designed to return a specific value. In the event that the returned value is null or undefined, the function should then default to a pre-determined value. function test<A, B>(input: A, fallba ...

Enhance Angular's User Interface using the Express Backend

I am a beginner in the MEAN stack development. I have set up an express server (api) that listens at a specific URL and handles incoming data. My goal is to create a frontend for this API where I can send and display incoming data, logs, and current proc ...

Trouble with executing simple code in a new project (binding, input, ng model) across different browsers

I am encountering an issue with this code snippet. It's a simple one - I want to display the input text in my view, but nothing is showing up. The code runs fine in an online simulator, but when I try it in my browser, it doesn't work at all. I&a ...