When the button is pressed, the TypeScript observable function will return a value

Check out the snippet of code I'm working with:

removeAlert() : Observable<boolean> {
    Swal.fire({
      title: 'delete this file ?',
      text: 'sth',
      icon: 'warning',
      showCancelButton: true,
      confirmButtonText: 'ok',
      cancelButtonText: 'cancel'
    }).then((result) => {
      if (result.value) {
        return of(true);
      } 
      else if (result.dismiss === Swal.DismissReason.cancel) {
        this.showError("canceled" , "sth else");
        return of(false);
      }
    });
    //return of(false);
  }

I'm trying to figure out how to observe the value after a click and return it.

Specifically, I need help with this part if(result.value)

Answer №1

To implement a Subject and trigger a next value within an if/else statement, you need to make sure to call .subscribe() on the Subject before emitting a value. In the provided code snippet, the subscription is set up in the ngOnInit lifecycle method:

myBool: boolean;
mySubject: Subject<boolean> = new Subject();

ngOnInit() {
  this.mySubject.subscribe(value => console.log('Value: ', value));
}

removeAlert() {
  if (this.myBool) {
    this.mySubject.next(true);
  } else {
    this.mySubject.next(false);
  }
  this.myBool = !this.myBool;
}

Make sure to bind the click event to the removeAlert() method in your component template:

<button (click)="removeAlert()">Click me</button>

You can also check out this stackblitz demo for a working example of the above implementation.

Answer №2

I am curious about your desired outcome. Perhaps utilizing a Subject object would be helpful.

private subject = new Subject<boolean>();


swal.fire({
...
})
.then(() => this.subject.next(true))

You can then proceed to subscribe to the subject.

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

Dealing with Cross-Origin Resource Sharing Problems in Angular 8 REST API

I am currently working with 2 components: The first component, "CurrenciesComponent," is being loaded. @Component({ selector: 'app-currencies', templateUrl: './currencies.component.html', styleUrls: ['./currencies.componen ...

Error in Typescript: Property 'timeLog' is not recognized on type 'Console'

ERROR in src/app/utils/indicator-drawer.utils.ts:119:25 - error TS2339: Property 'timeLog' does not exist on type 'Console'. 119 console.timeLog("drawing") I am currently working with Typescript and Angular. I have ...

Exploring the power of Angular: Combining multiple observables seamlessly

I have a trio of services that return observables. The initial service retrieves a list of recipes, the second service fetches all ingredients for a specific recipe, and the final one acquires the quantity of a specific ingredient type. My goal is to call ...

The correct procedure for refreshing a page in Angular 8

Note: I found some code snippets online but, after testing them out, I have doubts about their reliability due to inconsistencies. In my script, I have developed two utility functions - one for moving to the parent node and another for reloading the curre ...

What is the best way to implement an Angular Guard that utilizes an API service for validation and redirects in case of failure?

Hello there! I am currently working on an Angular 7 application that deals with time cards. One of the main features I have implemented is a CanActivate Guard for controlling access to certain components. The CanActivate code utilizes Observables to decid ...

Finding the location of an "Apply" button on an Angular HTML page

There is an issue with the positioning of the apply button in the filter bar. Sometimes it displays in the next row instead of alongside the other filters. How can I determine the exact position of this apply button within the HTML page? <div class=&quo ...

Navigating through the nested object values of an Axios request's response can be achieved in React JS by using the proper

I am attempting to extract the category_name from my project_category object within the Axios response of my project. This is a singular record, so I do not need to map through an array, but rather access the entire object stored in my state. Here is an ex ...

Unable to establish a connection between the HTML element and the TypeScript variable

I'm facing an issue with my code where the function that worked perfectly for register and login is not functioning properly on the index page. Even though there seems to be no errors in the login and register functions, I have a form with an input s ...

Struggling to add phantom-js to my Angular project

I'm looking to incorporate the phantomJS library into my Angular 4 project for continuous integration with Jenkins. No matter what method I try, I keep encountering the same (or similar) error. For instance, when following this tutorial and attemptin ...

Angular 2 is encountering issues with reading and displaying unicode characters (ud83dude31 or u0C28u0C3E) from the http response onto the user

My current task involves extracting unicode data from an http response, specifically for emojis. The response is in the form of a property-value pair within an object, with the message content being presented as JSON data ("messageContent":"hello \&bs ...

The Fusion of Apollo GraphQL Server and TypeScript: A Match Made

Lately, I've been immersed in a project that utilizes the node.js + express + typescript + Apollo server stack. During my research on Apollo client, I came across the TypeScript section, but surprisingly found little information regarding TypeScript f ...

Error: Code layer not located while utilizing "sam invoke local" in AWS

Currently, I am engaged in an AWS project where I am developing two lambda functions. Both of these functions rely on a common codebase stored in the node_modules directory, which is placed in a separate layer named AWS::Lambda::LayerVersion, not to be con ...

best practices for filtering custom data returned from valuePreparefunction in ng2 smart table

Having an issue with the filter in ng2 smart table because I am returning custom data from the valueprepareFunction. This is my setup... columns: { id: { title: 'Id', type: 'string' }, surname: { title: 'surname', ty ...

Ways to identify the moment a form becomes 'ready' after the component has been initialized

It seems like I might be making a mistake, as there are instances where I need to make adjustments to a Form or FormControl after a component has initialized and data has been loaded. The problem arises because the form and its controls don't seem to ...

From HTML element to pug-template with the use of the # symbol

I have a code snippet with 2 angular material radio buttons. Both of them contain the #attribute/element (I'm not sure what it's called) within them. How can I convert them into pug so that the attribute/element with the # works? Below is the sam ...

Encountered a mistake while trying to deploy an Angular 2 application on Heroku - received an error message indicating an expected expression but instead got

I am encountering an issue with my Angular 2 app. It runs perfectly fine locally, but when I deploy it on Heroku, I'm getting the following errors: >SyntaxError: expected expression, got '<' ><!DOCTYPE html> >shim.min.js ( ...

Comparing TypeScript and C++ in terms of defining class reference member variables

class B; class A { A(B b_) : b{b_} {} B &b; }; In C++, it is possible to have a reference member variable like 'b' in class A. Can the same be achieved in TypeScript? Alternatively, is there a specific method to accomplish this in ...

Show information in a table based on a unique identifier

I am working with some data that looks like this [ { date: '20 Apr', maths: [70, 80.5, 100], science: [25, 20.1, 30] }, { date: '21 Apr', maths: [64, 76, 80], science: [21, 25, 27] }, ]; My goal is to present ...

Pile of automatically generated elements

Within our application, a dynamic panel has been implemented to load various forms. The panel service is responsible for receiving information about which form to load, and the panel component then handles the creation and loading of the specific form usin ...

Troubleshooting error messages in Angular related to scss ModuleBuild

I've been working on applying a theme to my Angular application, but I've run into an issue. It seems that the src/theme.scss file I created is functioning correctly on its own. However, when I try to import "~@angular/material/theming", I encoun ...