Can you explain why it prints to the console twice every time I try to add an item?

This is a note-taking application created using Angular and Firebase. The primary functionalities include adding items and displaying them. I noticed a strange behavior where my ngOnInit() method is being called twice every time I add an item. As shown in the screenshot, the console.log(this.notepads) statement is triggered twice upon adding an item.

Do you think there is an issue causing the ngOnInit() method to be called twice, or is it expected behavior?

import { Component, OnInit } from '@angular/core';
import { NotepadService } from 'src/app/services/notepad.service';
import { Notepad } from 'src/app/model/note';
@Component({
  selector: 'app-add-note',
  templateUrl: './add-note.component.html',
  styleUrls: ['./add-note.component.css']
})
export class AddNoteComponent implements OnInit {
  title:boolean=false;
  noteTitle:string;
  noteDescription:string;
  constructor(private notepadService:NotepadService) { }

  ngOnInit(): void {
  }
  onSubmit() {
    if(!this.title || !this.noteTitle) {
      alert('Task is empty')
    } else {
    let note:Notepad = {
      title:this.noteTitle,
      description:this.noteDescription
    }
    this.noteTitle = ''
    this.noteDescription = ''
    this.title = false
    this.notepadService.addNote(note)
  }
}
}
import { Component, OnInit} from '@angular/core';
import { NotepadService } from 'src/app/services/notepad.service';
import { Notepad } from 'src/app/model/note';
import { NgForm } from '@angular/forms';
@Component({
  selector: 'app-notepad',
  templateUrl: './notepad.component.html',
  styleUrls: ['./notepad.component.css']
})
export class NotepadComponent implements OnInit {
  notepads:Notepad[]=[];
  modal:boolean=false;
  selectedNote:Notepad= {
    id:'',
    title: '',
    description: ''
  };
  constructor(private notepadService:NotepadService) { 
  }
  
  ngOnInit(): void {
    this.notepadService.getNotepads().subscribe(notepad=> {
      this.notepads=notepad
      console.log(this.notepads)
    })

  }

  onSelect(note:Notepad){
    this.modal = !this.modal
    this.selectedNote = note;
  }

  onSubmit(reg:NgForm) {
    const note = reg.value;
    note.id = this.selectedNote.id
    this.notepadService.updateNote(note)
    this.modal = false

  }
  removeNote() {
    if(confirm('Are you sure?')) {
      this.notepadService.deleteNote(this.selectedNote)
      this.modal = false
    }
    this.modal = false

  }

}

Answer №1

NotePadService is likely an observable type, meaning that any changes to the observable's properties will automatically update the UI (in this case, the console log). This leads to two console logs being displayed.

// The subscribe() method belongs to the Observable type, allowing data to be asynchronously or synchronously streamed to components or services that have subscribed to the observable.

this.notepadService.getNotepads().subscribe(notepad=> {
      this.notepads=notepad
      console.log(this.notepads)
    })

The observable is assigned in the constructor:

private notepadService:NotepadService

Initially, when the page loads, a console log is generated calling the notpadservice.

Subsequently, when a note is added, the observable's property is updated, leading to another console log.

In response to the question of whether ngOnInit() is called twice:

No, the two console logs are due to the nature of the observable type.

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

Experiencing difficulties in constructing a project through Angular-CLI on a Windows operating system

Encountering an error while attempting to install angular-cli with the command: npm install -g angular-cli The error message received is as follows: npm ERR! Windows_NT 10.0.14393 npm ERR! argv "C:\\Program Files\\nodejs\\n ...

The TS2339 error has occurred because the "email" property cannot be found on the specified "Object" type

I encountered an issue while using Angular 5, here is the code snippet : signIn(provider) { this._auth.login(provider).subscribe( (data) => { console.log(data); this.hideForm = false; this.emaill = data.email; ...

Switching the Checkbox Data Binding Feature in Angular

I am looking to send a value based on a toggle switch checkbox selection between Hourly or Salary. How can I incorporate this into the form below? html <div class="row"> <div class="col-sm-6"> <div cl ...

To populate an Ionic list with items, push strings into the list using the InfiniteScroll feature

Looking for help with implementing infinite scroll in a list? I am using the ion-infinite-scroll directive but struggling to push string values into my list. The list contains names of students in a classroom. Can anyone provide guidance on how to push str ...

Troubleshoot: Firebase deployment of Vue.js application unable to locate page

I'm currently working on a silly web app with my friends for some laughs. We're using Firebase hosting and Discord OAuth2. The issue arises when attempting to access the "/login" page either by entering it in the URL or clicking "authorize" on th ...

The ngModel feature is not functioning properly when trying to update in tag inputs

I am having trouble with two-way data binding using ngModel in tag-inputs. Can someone please assist me? Here is the link to my code on StackBlitz ...

Unable to locate the "lint" target for the project selected OR The data path "" must contain the necessary property 'lintFilePatterns'

Upon transitioning my Angular project structure to a monorepo setup as demonstrated in this tutorial, I encountered several configuration issues that required extensive troubleshooting to resolve. The first error message stated: Cannot find "lint" target ...

Guide on setting up an AWS code pipeline for Elastic Beanstalk deployment on ASP.NET Core 5.0 with Angular

I am facing a challenge with deploying my ASP.NET Core 5.0 application with Angular to the EBS Windows environment using AWS CodePipeline (CI / CD). Despite searching various internet resources for solutions, I have not been able to find much help. My att ...

What is causing pre-defined variables to act unexpectedly in Cypress?

Encountering unexpected results while pre-defining element variables and using them later in Cypress 10 with Cucumber. Let's take a look at this login test: Given("I'm logged in as Default user", () => { cy.visit('/ ...

What is the process for retrieving information from a subcollection in Firestore?

I have recently developed a web application using Node Express for the backend and Reactjs for the frontend. The Firestore database contains a "users" collection with multiple documents for each user, including fields and subcollections. 1st view https:// ...

The deployment issue with Firebase Function Gen2 is causing roadblocks

Currently, I have several firebase functions from Gen1 operating smoothly, but when I attempted to add a new function using Gen2 today with the intention of upgrading all my existing Gen1 functions, I encountered an error during deployment: shutdown reques ...

Maintaining the Continuity of an Observable Stream Post Error Emission

Have you ever wondered how to handle errors from an observable without ending the stream? For instance, when making HTTP calls and encountering a 404 error or another type of error, throwing an error in the stream will cause it to stop and trigger the err ...

What is the best way to maintain scrollbars on mobile devices?

I'm currently building a cross-platform application using Angular 4 that needs to work seamlessly on both mobile and desktop devices. Is there a special trick to prevent the scrollbars from disappearing when viewing this page on a mobile browser? I&ap ...

Encountering CircularJSON Error While Creating Angular CLI 7 Project

Recently updated Angular CLI to version 7.1.1 and encountered an issue when trying to create a new project using ng new project-name. The error message displayed is: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cf ...

Angular: Variable `app` has not been defined

I am working on a simple MEAN stack app and it is almost up and running, but I encountered an uncaught reference error when it tries to redirect to the index page. The server seems to be running fine and the browser displays "Loading..." as expected on the ...

The translation of popups using ngx-translate in Javascript is not functioning properly

When I click on my request, the content "Are you sure?" is not changing to the required language. This issue is located in list.component.html <button type="button" (click)="myrequest(item.Id)">Request View</button> The fu ...

Issue with Angular2 discount calculation formula malfunctioning

I'm encountering a rather perplexing issue with Angular2/Typescript. My goal is to compute the final price based on a specified discount value. Here's the formula I am using: row.priceList = row.pricePurchase + (row.pricePurchase * row.markUp / ...

What is the best way to create a routerlink that is both single-clickable and double-clickable within an

There have been numerous instances where a similar question has been raised, but I am unable to make this work. Despite looking at various answers such as this one on Stack Overflow that don't seem to work for most users. While this may not be specifi ...

What benefits do Definitely Typed TypeScript files offer for Knockout and jQuery?

I'm not sure if this is a silly question, but I was wondering if it's necessary to use definitely typed (.d.ts) versions of external libraries when working with Typescript. Currently, my code base uses jQuery and Knockout in the traditional manne ...

What makes TypeScript believe that the variable could possibly be undefined when it is clearly not the case?

I recently encountered an issue where TypeScript incorrectly identifies a variable as possibly being undefined. Here is a simplified example: const func = (val1?: boolean, val2?: boolean) => { if (!val1 && !val2) return; let result: boolean; ...