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

What causes an inference site to have varying effects when accessed directly versus when it is retrieved from a function?

Below is the provided code snippet : declare class BaseClass<TValue = any> { value: TValue; foo(value: TValue): void; } type Wrapped<T> = { value: T } declare class ConcreteClasss<TValue> extends BaseClass<TValue> { construc ...

What are the best strategies for managing npm dependencies alongside other packages?

I am working on an Angular app that has the following dependencies: "dependencies": { "personalUiLibrary": "1.0.0" }, "devDependencies": { "tailwindcss": "^2.2.7" } In the personalUiLibrary p ...

What steps are involved in implementing ts-transformer-keys in a Next.js project?

I am trying to extract keys from an interface as a string array so that I can iterate over them. After doing some research on stackoverflow, I found out that I need to use a library called 'ts-transformer-keys'. In my Next.js project, which invol ...

Navigating back in an Async Function within Angular

I am encountering an issue while trying to incorporate an if else condition within my async function in Angular. To prevent the error, I am required to include a return statement in my async function. asyncFunction: (value) => { let getApplica ...

Start Transloco in Angular before the application begins

For our Angular project, we have implemented Transloco to handle translations. Within my typescript code, I am using the transloco service in this manner: this.translocoService.translate('foo.bar') I understand that it is crucial to ensure that ...

Following the upgrade to Angular 9, the Typescript file no longer transpiles with the esnext module

My project includes a typescript file named git-version.ts at the root location, essential for the Jenkins CI pipeline to extract information about the latest commit triggering the CI build. The structure of my project is as follows: root |_src/ |_angul ...

What is the best way to manage the connections in my D3 tree chart?

I've been working on customizing a tool from an open source library called angular-d3-tree, but I'm struggling with getting the links to connect properly in my D3 tree structure. This is what my current tree layout looks like: https://i.stack.im ...

Alter the language settings of the Datepicker feature in Material Angular 4

Need help changing the language of Datepicker in Material Angular. Struggling to locate this information in the Angular material 2 documentation. Check out this plunkr https://plnkr.co/edit/unzlijtsHf3CPW4oL7bl?p=preview <md-input-container> < ...

Creating a default option of "please select" on an Angular select element with a null value for validation

Within my Angular application, I am using a select element with an ngFor loop: <select formControlName="type" required> <option *ngFor="let type of typeList" [ngValue]="type.value">{{ type.caption }}</option> </select> When view ...

Ways to resolve the issue of 'message' property lacking an initializer in TypeScript without suppressing errors

Currently, in the process of using TypeScript and Sequelize to create a model within Node.js. import { Table, Column, Model, AllowNull } from 'sequelize-typescript'; @Table class Person extends Model { @Column @AllowNull(false) name: strin ...

What is the most efficient way to find the sum of duplicates in an array based on two different properties and then return the

var data = [ { "amount": 270, "xlabel": "25-31/10", "datestatus": "past", "color": "#E74C3C", "y": 270, "date": "2020-10-31T00:00:00Z", "entityId": 1, "entityName": "Lenovo HK", "bankName": "BNP Paribas Bank", "b ...

What is the best method for saving and retrieving a class object in a web browser's storage?

Looking for a way to create page-reload proof class instances in my Angular 2 application. Within my component's .ts file, I have defined the following classes: export class AComponent implements OnInit { foo: Foo = new Foo(); ngOnInit() { / ...

The combination of Stripe, Angular, and TypeScript is not compatible

Attempting to utilize Stripe.card.createToken() in order to generate a token for backend usage has proven to be challenging. Integrating this functionality with Angular and TypeScript requires careful coordination. Currently, the angular-stripe and stripe. ...

What is the reason for the Enter key being assigned to the incorrect button?

In my Angular 13 form, there are several buttons. One of them is used to add a new row to the form: <div class="col-md-2 offset-md-8"> <button class="badge rounded-pill bg-secondary mt-2" (click)="addRow()& ...

Is it possible to enhance the GamepadAPI's functionality?

I've been working on enhancing the built-in GamepadAPI by adding custom controller code. With TypeScript, I created a basic function to trigger a "gamepadconnected" event. // emulate gamepadconnected event function dispatchGamepadConnectedEv ...

What is preventing me from retrieving data from a modal in Ionic/Angular?

I'm currently in the process of designing a modal that allows users to input a quantity for an item using a form. The functionality is working as intended, but I am encountering an issue with getting the server data back into the page. Despite my bes ...

Using ngFor to iterate over an array after it has been loaded

Currently, I am attempting to generate a list of cards after loading an array. Take a look at my code snippet: locations; constructor( private toolbarTitle: ToolbarTitleService, public popoverController: PopoverController, private syncServi ...

Discovering dependencies for the Tabulator library can be achieved by following these

Can anyone provide me with a complete list of dependencies for Tabulator 4.2? I have already reviewed the package.json file, but it only contains devDependencies. ...

Step-by-step guide for importing a JSON file in React typescript using Template literal

I am facing an error while using a Template literal in React TypeScript to import a JSON file. export interface IData { BASE_PRICE: number; TIER: string; LIST_PRICE_MIN: number; LIST_PRICE_MAX: number; DISCOUNT_PART_NUM: Discout; } type Discoun ...

Importing the isPropertyUpdated method in Angular 4

My challenge lies in utilizing the isPropertyUpdated function within Angular 4. However, I have encountered a roadblock as Angular 4 does not facilitate deep imports. An example of an import that fails to work on Angular 4 is: import {isPropertyUpdated} ...