Subscription to Observable content failed to run

When a submit button is clicked inside the component HTML, it triggers a function called addCollaborators(). The code for this function can be found below:

component.ts

emails: string[] = [];

constructor(public userService: UserService) {}

// Function triggered by the HTML
addCollaborators() {
  this.emails.forEach(email => {
    const user = this.getUserFromEmail(email);
    if (user instanceof User) {
      this.counterService.someDbFunction();
    }
  });

  this.dialogRef.close();
}

getUserFromEmail(emailAddress: string): User | void {
  console.log("Code reaches here");
  this.userService.users$.subscribe((users: User[]) => {
    console.log("This part is never executed");
    for (const user of users) {
      if ( /* Some boolean logic */ ) {
        return user;
      }
    }
  });
}

user.service.ts

users$: Observable<User[]>;

The log statements indicate that the code within the subscription inside getUserFromEmail is not being run. This can be seen as the operations are not performed and there is no message in the console. The users$ observable is successfully filled within the service constructor and subscribed to elsewhere. For example, the following line in the constructor of component.ts works:

this.userService.users$.subscribe(users => console.log(users));

If you need any more information or have suggestions, please let me know. Thank you!

Update

The code snippet below will not produce any logging, hinting at a deeper problem than initially anticipated.

addCollaborators() {
  console.log("I am logged");
  this.userService.users$.subscribe(users => console.log("I am not", users));
}

Here is the relevant HTML:

<button mat-fab
        (click)="addCollaborators()"
        class="add-collaborators">
<mat-icon>group_add</mat-icon>
</button>

Answer №1

Take a look at the live Stackblitz example; Feel free to enhance this demo with your own code and check for any potential errors...

Please include an Error & Finally block (as shown below) in your subscription to handle any errors that may occur...

  getUserFromEmail(emailAddress: string): User | void {
    console.log("Code execution begins for "+ emailAddress);
    this.userService.users$().subscribe(

  /* DATA BLOCK */    
  (users: User[]) => 
  {
  console.log("This part is not reachable");
    for (const user of users) {
      /* if ( //Some boolean logic ) { return user; } */
    }
  } 
  /* ERROR BLOCK */    
  , errr => { console.log(errr); }
  /* FINALLY BLOCK */    
  , () => { console.log("this is the finally block");}
);

}

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

Leveraging @ContentChildren in Angular 2 to sort through a component's contents

I am currently working on implementing a search component that can trigger a search(term: string) function on specific child components. If the search on the child fails, the function will return null; otherwise, it will return a reference to the child. M ...

Implementing the handling of multiple button events in a ListView through onclick function

Currently, I have a listview with three buttons that need to trigger the same method checkInstall on multiple button clicks. However, I am unsure of how to achieve this. Below is the relevant code snippet: html file: <ListView [items]="allAppsList" c ...

How to Share Angular Modules Between Two Projects with Ivy Compilation Necessity

Query: I am faced with the challenge of sharing common modules between two Angular projects, one of which requires full Ivy compilation to function properly. To manage these shared resources, we have set up a private GitHub NPM repository. However, becaus ...

Having trouble compiling a Vue.js application with TypeScript project references?

I'm exploring the implementation of Typescript project references to develop a Vue application within a monorepo. The current structure of my projects is outlined below: client/ package.json tsconfig.json src/ ... server/ package.json t ...

Issue with Angular: boolean value remains unchanged

Currently, I'm encountering an issue with my application. My objective is to establish a list containing checkboxes that toggle their values between true and false when clicked. Sounds simple enough, right? Below is the HTML code snippet: <l ...

Errors encountered when attempting to update Angular from version 5 to version 6

After following the update guide, I encountered some errors that I am unsure about. https://i.stack.imgur.com/jc65s.jpg To resolve the issues, some have recommended installing rxjs-compat, but unfortunately, this only led to more errors: https://i.stack ...

Using Apache to rewrite wildcard subdomains for an Angular application

I am currently facing a challenge with my Angular app that needs to be set up under subdomains for multi-tenant support. Each subdomain represents a different tenant within the application. At present, I have an .htaccess configuration that successfully lo ...

Issue: The token is required in Angular 2 RC5 to proceed with the testing

In June 2016, an article was written on testing Angular 2 applications using angular2-seed as the starting point. For a tutorial rewrite using Angular CLI (master branch) with Angular 2 RC5, a strange error is encountered during testing: Error: Token mus ...

How to temporarily modify/add CSS class in Angular 2

In my Angular 2 application, there is a label that displays the current amount of points for the user. Whenever the number of points changes, I want to briefly change the class of the label to create an animation effect that notifies the user of the chang ...

Unable to push items to an array in Angular

I am currently working with a Java service that retrieves data from an Oracle database. The goal is to display the results in an Angular application using an array of objects: resultSet:Info[]=[]; Here is the code for the service: pastHourInfo() { ...

Creating Typescript libraries with bidirectional peer dependencies: A complete guide

One of my libraries is responsible for handling requests, while the other takes care of logging. Both libraries need configuration input from the client, and they are always used together. The request library makes calls to the logging library in various ...

Is it possible to create a single directive that can handle both Structural and Attribute behaviors?

Trying to develop an Angular Directive that will handle various functionalities based on config input values Dynamically add elements to the DOM based on input values (similar to ngIf) Apply styling to rendered elements Add attribute properties such as d ...

Transmitting messages from a cross-domain iframe to the parent window

In my parent component, I am embedding an iframe from a different domain. The iframe contains a button that when clicked, I need to capture the event and pass it back to the parent component. I have experimented with using window.postMessage and window.ad ...

Is KeyValueDiffers within DoCheck limited to working with just a single object per component?

Initially, my ngDoCheck method worked perfectly with just this line: var productChanges = this.differ.diff(this.myProduct); Then I decided to add another object from my component and included the following line: var companyChanges = this.differ.diff(thi ...

Tips for accessing other environment variables within the environment.ts file in an Angular project

Currently, I am working on modifying the 'environment.ts' file within an Angular project to include additional properties. The current setup looks like this: export const environment = { production: false, apiUrl: 'http://example.com&ap ...

The 'mat-table' component is triggering an error indicating that the 'dataSource' attribute is unrecognized in the table

Recently, I have been diving into the world of Material Library for Angular. Working with Angular version 15.0.1 and Material version 15.0.1, I decided to include a mat-table in my form (schedule.allocator.component.html): https://i.stack.imgur.com/c7bsO. ...

Executing ts-node scripts that leverage imported CSS modules

Is there a way to execute scripts that utilize css modules? I am currently working on a typescript migration script that I would like to execute using ts-node. The ideal scenario would be to keep the script's dependencies separate from the React comp ...

Out of the blue, Angular has inexplicably ceased to function in development, production, and local environments, despite successfully

TypeError: n is not iterable TypeError: n is not iterable I am currently working on an Angular and Node.js project hosted on Heroku. Everything was running smoothly until recently when I encountered an error after successfully building Angular. Upon loadi ...

ESLint refuses to be turned off for a particular file

I am in the process of creating a Notes.ts file specifically for TypeScript notes. I require syntax highlighting but do not want to use eslint. How can I prevent eslint from running on my notes file? Directory Structure root/.eslintignore root/NestJS.ts r ...

Tips for setting variable values in Angular 7

I'm encountering an issue with assigning values to variables in my code. Can anyone provide assistance in finding a solution? Here is the snippet of my code: app.component.ts: public power:any; public ice:any; public cake:any; changeValue(prop, ...