Angular 2 has its own version of $q.when called RxJs

Back in the AngularJS 1.* days, I used to have this code snippet to refresh the auth-token:

...

if (!refreshTokenInProgress) {
  refreshTokenInProgress = AuthService.refreshToken();
}


$q.when(refreshTokenInProgress, function () {
  refreshTokenInProgress = null;

  // re-send requests with error
  ...
}, function () {
  // logout if refresh token rejected

  refreshTokenInProgress = null;

  ...
});

...

How do I convert this code to use Observables in Angular 2?

I'm stumped because this approach doesn't seem to be working:

if (!refreshTokenInProgress) {
  refreshTokenInProgress = AuthService.refreshToken().subscribe();
}

Observable.forkJoin([this.refreshTokenInProgress]).subscribe(
  success => this.refreshTokenInProgress = null
);

What is the equivalent of $q.when in RxJs?

Answer №1

When you use Observable.of(data), it is similar to using $q.when.

If you're interested, you can check out my article on transitioning from $q to RxJS at $Q map to RxJS

Here's an example taken from actual code:

spyOn(myService, 'getData').and.returnValue(Observable.of([{id: 1}, {id: 2}]));

Here's a slightly more intricate example:

   deleteRole(role: Role) {
Observable.fromPromise(this.confirmDialogService.open(DELETE_ROLE_TITLE, DELETE_ROLE_CONFIRM_BODY({name: role.name}))
  .switchMap(result => result ? Observable.of(result) : Observable.empty())
  .switchMap(() => this.rolesService.getUsersForRole(role.id))
  .switchMap(({elements: users}) => {
    return _.isEmpty(users) ?
      Observable.of(users) :
      Observable.fromPromise(
        this.confirmDialogService.open(ROLE_IN_USE_TITLE,
          ROLE_IN_USE_CONFIRM_BODY({users: users.map(({firstName, lastName}) => `${firstName} ${lastName}`)}),
          {hideCancelButton: true})
      ).switchMap(() => Observable.empty());
  })
  .switchMap(() => this.rolesService.deleteRole(role))
  .subscribe(data => {
      this.toastr.success(`Role '${role.name}' is deleted`, 'Success');
      this.findallRoles(); //Refresh role grid;
      this.roleDeleted.emit();
    },
    error => {
      this.toastr.error(error, 'Error (rolesService.delete)!', {dismiss: 'click'});
      console.error(error);
    });

}

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

Modifying the onclick event of a button: A guide

Once a user selects the Add button located below the photo, that specific image is to be appended to the table adjacent to the list and subsequently transforms the add button into a REMOVE button. eg. Current status: https://i.stack.imgur.com/8eJoS.png ...

What is the most effective way to access a variable from a service in all HTML files of Angular 2/4 components?

In my angular 4 project, I have an alert service where all components can set alerts, but only specific components display them in unique locations. My question is: how can I access a variable from this service across all HTML files? The structure of my s ...

Limit function parameters to only accept values with matching keys

I am relatively new to using TypeScript and am currently working on a project that involves handling various shapes of data from different sources. My goal is to pass this data to different aggregator classes, with one aggregator class corresponding to eac ...

Include the image source in the array

Currently, I am utilizing this loop to showcase images using Smarty {foreach from=$gallery item=image key=KEY} <div class="col-lg-2 col-md-2 col-sm-4 col-xs-6 smallImage"> <img ng-click="bigImage('/files/galleries/{$image.gallery ...

Error in AngularJS service: unable to find method 'save'

I am currently utilizing AngularJS version 1.0.7 and below is how I have configured the service: angular.module('myAngularJSApp.services',['ngResource']) .factory('RegisterNumber', ['$resource', function($resour ...

Creating a unique directive to customize the height

I'm currently working on a directive called appHeaderResize, which is designed to calculate the height of both the <app-online-header> component and the <app-navigation> component. Below is the code snippet: <div class="sticky" appHe ...

"Seeking advice on how to nest a service provider within another one in AngularJS 2. Any

I am faced with a product and cart list scenario. Below is the function I have created to iterate through the cart list and retrieve the specific product using its ID. getCartList(){ this.cart = CART; this.cart.forEach((cart: Cart) => ...

What is the best way to extract data from API console output using Angular?

Currently, I am deeply involved in a full stack project utilizing asp.net and angularjs. My goal is to extract output response from the Swagger API. You can view the code I've written for this purpose here: (https://i.stack.imgur.com/vLyIE.png) The A ...

The function signature '() => Element' is incompatible with the type 'string'

Greetings! I have a standard function that returns a span with a prop (if I'm not mistaken). In my TS code, I am encountering this error: Error image Below is the code from the file named qCard.tsx: import { QuestionAnswerTwoTone } from "@material- ...

Exploring Angular data iteration with Tab and its contentLearn how to loop through Tab elements

Upon receiving a response from the API, this is what I get: const myObj = [ { 'tabName': 'Tab1', 'otherDetails': [ { 'formType': 'Continuous' }, { 'formType& ...

AngularJS Currency Converter - Converting Currencies with Ease

I have a question regarding the most efficient way to handle currency conversion on a webpage. Currently, I have multiple input fields displaying different currencies. When a user clicks on the currency conversion button, a modal popup appears. After the ...

"Modifying the form of an item by adjusting its variable, and rendering certain object properties as

let myObj = { a: { value: 1 }, b: { value: 2 } } myObj = { // How can I make the property b optional in myObj without specifying my own type? a: { value: 123 } } Is there a way to make the property myObj.b ...

Monitoring variables in different AngularJS controllers

I have a component named histogram demo which includes a distinct controller with a variable known as $scope.selectedElements. I aim to monitor this variable in the primary appCtrl controller. How can I achieve access to this variable without using $rootSc ...

When I delete the initial element from the array, the thumbnail image disappears

Using react-dropzone, I am attempting to implement image drag and drop functionality. The dropped image is stored in the React state within a files array. However, a problem arises when removing an image from the array causing the thumbnails of the remain ...

Solving the issue of loading Ember Initializers during the transition to TypeScript

While following the ember quick start tutorial, I attempted to switch from Javascript to Typescript. Converting the .js files to .ts files resulted in an error with the ember-load-initializers import. The application is unable to run until this issue is re ...

Steps to create a function in a .js file that uses ng-show conditions

I am in the process of validating a web page where the user inputs must be alphanumeric, have a maximum length of 45 characters, and be unique. Below is the code snippet I am working with. Is there a way to consolidate these three ng-show conditions into ...

Oops! Looks like there's an issue with the type error: value.forEach is

I am working on creating an update form in Angular 6 using FormArray. Below is the code snippet I have in editfrom.TS : // Initialising FormArray valueIngrident = new FormArray([]); constructor(private brandService: BrandService, private PValueInfoSe ...

Continuously encountering CORS errors despite activating them, using .NET Core in conjunction with an Angular client

I recently encountered a CORS issue in my .NET Core 3.0 Web API project despite having enabled CORS in the startup file. Here's how I configured it: ConfigureService services.AddCors(options => { options.AddPolicy("AllowOrigin", builder => b ...

Deleting an element from an object in TypeScript

Is there a way in TypeScript to exclude certain elements (e.g. 'id') from an object that contains them? ...

ng-change does not fire a second time when the value is updated using event.target.value

I am attempting to clear the value of an input:textbox if a non-numeric value is entered. I have implemented ng-change to validate the input. Below is the code snippet: <input type="text" ng-change="onChange(this.P)" ng-model="P" class="col-xs-4 col-sm ...