Can you explain the significance of subscribing and subscribe in Angular? Also, clarify when is the appropriate time to use them - in the constructor or ngOnInit method

After encountering numerous instances of code containing the subscribe method in Angular, I began to wonder about the consequences of not utilizing them. What are we potentially missing out on?

I've noticed that all the code snippets using subscribe are written within the constructor rather than ngOnInit. Why is this practice so common?

constructor(private router: Router) {
  m_Router.events.filter(event => event instanceof XComponent)
    .subscribe(e => {
      ...
    });
}

Answer №1

Angular's features heavily rely on observables, allowing for asynchronous code execution. Failing to subscribe to a property like m_Router.events will result in no value being returned, as an observable needs something to subscribe to.

I typically recommend placing all logic that should run when a component loads within the ngOnInit method, reserving the constructor for tasks like dependency injection. For a more detailed explanation, check out this post: Difference between Constructor and ngOnInit

Another important point about subscribers and subscriptions is that you should manually unsubscribe from them when the component unloads. While Angular handles this automatically for HttpClient subscriptions, for others like m_Router.events, you should use ngOnDestroy to unsubscribe. To do this, store the subscriber in a variable when subscribing to it.

Answer №2

One effective approach for subscribing to services is by utilizing the ngOnInit() lifeCycle hook method,

For more information on Angular services, you can refer to the official documentation which provides an example of a service called getHeroes:

Learn more about services here

Utilize ngOnInit for function calls It is recommended to invoke getHeroes() inside the ngOnInit lifecycle hook rather than in the constructor.

Keep the constructor simple It is advisable to keep the constructor straightforward and only use it for basic initialization tasks like assigning values to properties. The constructor should not contain any complex logic or functions that make HTTP requests to external servers.

Instead, perform the getHeroes() call within the ngOnInit lifecycle hook to ensure that it is executed at the appropriate time after creating a new instance of HeroesComponent.

ngOnInit() {
  this.getHeroes();
}

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

How can I send a value to an Angular element web component by clicking a button with JavaScript?

I want to update the value of an input in an Angular component by clicking on a button that is outside of the Angular Element. How can I achieve this in order to display the updated value in the UI? Sample HTML Code: <second-hello test="First Value"&g ...

Encountered an issue while saving a blob in NativeScript: "Unable to convert object to [B at index

I have a Nativescript Angular application that is downloading a PDF from a Rails server in Blob Uint8Array format. When I attempt to save it, I encounter the following error: JS: /data/user/0/com.asset.management/files/result.pdf JS: ERROR Error: Uncaught ...

Angular 2 - Post-Constructor Lifecycle Event Triggered

I am currently working on a project using Angular 2. After calling the component's constructor, I need to capture an event that indicates when the constructor call has completed. In my constructor, I am making a network call like this: import { Comp ...

Dealing with documents in Django Rest Framework

For my Angular + Django project, I am looking to add files to the Ticket model. Which field should I use for this – FileField? class Ticket(models.Model): titulo = models.CharField(max_length=100, blank=True) estagio = models.ForeignKey(Estagio, ...

Adding a new line in the configurations of MatDialogConfig (Angular)

Here is a code snippet: private mDialog: MatDialog, const dialog = new MatDialogConfig(); msg = "I enjoy coding in Angular.\r\n I am learning TypeScript." dialog.data = { message:msg }; alert (msg); mDialog.open(AB ...

Creating horizontal cards with Angular MaterialWould you like to learn how to design

I need help converting these vertical cards into horizontal cards. Currently, I am utilizing the Angular Material Cards component. While I can successfully create cards in a vertical layout, my goal is to arrange them horizontally. Below is the code sni ...

Retrieve the input type corresponding to the name and return it as a string using string template literals

type ExtractKeyType<T extends string, K extends number> = `${T}.${K}`; type PathImpl<T, Key extends keyof T> = Key extends string ? T[Key] extends readonly unknown[] ? ExtractKeyType<Key, 0 | 1> : T[Key] extends Record<str ...

Angular Gitlab CI/CD Pipeline Configuration with .gitlab-ci.yml

I'm new to continuous deployment with Gitlab and am trying to set up a pipeline for Angular. Everything is working smoothly except for the fact that I am unable to copy the dist folder from one location to another using the commands mentioned below. ...

Jasmine: The 'require' function has not been defined

I followed the angular2 quick start project tutorial found at: https://angular.io/guide/quickstart. The only difference is that I included the code var fs = require('js') in app.component.ts, and it worked. But when I attempted to write a Jasmin ...

Showing the attributes of the chosen items within an array using Angular

I am attempting to showcase the ID of the chosen items from the employee array, which is in a dropdown list. export const employees = [ {index:1,'name':"Josh",'id':"102A"}, {index:2,'name':"Sam",'id':"598A"}, {ind ...

What is the best method for accessing the properties of a JavaScript object based on input from a textbox?

Just starting out with angular and having trouble generating or updating a table based on text boxes. The schema includes country, sales, and profit fields. There are two text boxes for the x-axis and y-axis inputs. The table should dynamically update when ...

Angular Material UI: Nested Table Component

I am dealing with a table that has four static headers and two static columns. The data in the last two columns changes based on certain conditions. I need to convert this table into an Angular Material table. The first table is a standard HTML table. Th ...

What is the process for integrating TypeScript compiling into a JavaScript application?

My project includes a build.js file that is responsible for building the project. It has two main objectives: Compile .ts files and store them in a new directory. Create an asar archive containing the compiled files. Since typescript (or tsc) is availabl ...

What steps should be followed in order to generate a child or item with no assigned key

Here is my TypeScript code designed to automatically record the time of data creation: import * as functions from 'firebase-functions'; export const onAccCreate = functions.database .ref('/Agent/{AgentID}') .onCreate((snapshot, contex ...

Setting up TypeScript to function with Webpack's resolve.modules

Imagine having a webpack configuration that looks like this: resolve: { extensions: ['.ts', '.tsx', '.js', '.jsx', '.json'], modules: ['my_modules', 'node_modules'], }, You have a ...

Injecting properties into higher order functions in Typescript allows for the dynamic customization

I'm curious about the process of composing functions that take an object as the sole argument, where each higher order function adds a property. For instance, I have a function that takes a context as input. I would like to wrap this function with a w ...

You cannot assign type 'Node | null' to type 'Node' when attempting to loop through HTML elements in TypeScript

In my code, I am taking a raw Markdown string stored in 'markdownString' and using the marked.js library to convert it to HTML for display on a web browser. My goal is to extract all plain text values from the page and store them in an array of s ...

When trying to open the phonegap-plugin-barcodescanner on Android Studio with Ionic 6 and Capacitor, I encounter an error

Encountered an issue while trying to build the app in Android Studio. The error message "Could not find method compile() for arguments [{name=barcodescanner-release-2.1.5, ext=aar}] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.Defau ...

Exploring the functionalities of TypeScript's mapKey and pick features

I am looking to convert the JavaScript code shown below into TypeScript, but I don't want to use loadish.js. let claimNames = _.filter<string>(_.keys(decodedToken), o => o.startsWith(ns) ); let claims = <any>( _.mapKeys(_ ...

What is the best way to divide percentages accurately in Angular?

I am currently working on splitting percentages dynamically with Angular. For example, if txtBox1 has 75%, I want to split the remaining 25% between txt2 and txt3. If I change txt1 to 50%, then I want txt2 and txt3 each to receive 25%. The values may vary, ...