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

Ag-grid's external filtering feature allows users to easily apply

Initially, I attempted to integrate an external filter, but encountered issues where it wasn't functioning properly, resulting in the grid being stuck in a loading state. As a result, both the filter and grid are currently inaccessible. Currently, I ...

Using AngularJS with angular-google-maps to easily add markers through a form and locate your position with one click

I'm attempting to replicate the functionality demonstrated on since it fulfills 90% of my requirements. However, I'm facing some difficulties. While I can retrieve my location and log it in the console, a marker is not appearing on the map. Add ...

The nested div within the ui-view element is failing to expand to the entire width of the window

I am facing a challenge in making a child div stretch to the entire width of the window, rather than just the width of its parent. I am incorporating AngularJS with UI-Router, and I'm not sure if that is causing the issue. Attached is a screenshot. ...

Regular expressions that identify text located at the conclusion of a URL

Although the title may not be entirely appropriate, my goal is to create a regex that will remove any trailing '/' at the end of a URL under certain conditions. For example: http://stackoverflow.com/questions/ask/ to http://stackoverflow.com/qu ...

Display a page containing two distinct JSON arrays using Angular

Working with two separate JSON Arrays and incorporating them into a view using ng-repeat. The first JSON array contains text values used to generate fields. ["center", "80mm", "retain", "22pt", "bold", "140%", "18pt", "bold", "140%", "36pt", "11pt", "bol ...

Angular JS Troubleshooting: Application Not Functioning Properly

I've been learning AngularJS on codeSchool and I ran into an issue with my simple hello world app. It was working fine at first but then stopped completely. I can't seem to find the bug, so any help would be appreciated. Here is the HTML code: & ...

The $ionicModal fails to reflect any updates in the content when changes are made in the controller while the modal is open

My $ionicModal setup looks like this: <ion-modal-view> <ion-content> <ion-slide-box> <ion-slide ng-repeat="display in VideoCtrl.display track by $index" > <div class="card"> <div class="item item-divid ...

The spread operator seems to be malfunctioning whenever I incorporate tailwindcss into my code

Hi there! I hope you're doing well! I've come across a strange issue in Tailwindcss. When I close the scope of a component and try to use props like ...rest, the className doesn't function as expected. Here's an example: import { Butto ...

Leverage the power of TypeScript custom transformer and project reference for enhanced

I am currently working on a project that involves using both project references and custom transformers. The issue I am facing is that project references require the use of TSC for incremental compilation, but when TSC is used, the transformers are not app ...

Malfunction in parsing the post request body

Recently, I have been facing an issue while attempting to execute a $http.post request in this manner: $http({ method: 'POST', url: '//192.168.2.1:3000/auth/signup', data: $scope.credentials, headers: { 'Content- ...

Angular's $watch function does not receive the parameter 'newVal'

I have been facing an issue displaying messages from a backend response in an Angular AJAX call. I am using a ShareDataService to share data between different controllers. 'use strict'; var angularApp = angular.module('angularApp'); ...

Previewing files from external URLs with Ionic 5 Capacitor and Angular

I recently implemented the previewanyfile cordova plugin in my Ionic 5 application to open files from external URLs. While it works smoothly on Android devices, I have encountered an issue on iOS where some PDF files fail to preview and instead display a g ...

Eliminate the X-Powered-By:express response header from the Angular UI navigation URL

When using the application, I am not seeing the header x-powered-by in the response headers, which is functioning as intended. The issue occurs when a user refreshes the page, causing the x-powered-by header to be added to the response header in the devel ...

Angular Link Panel

I'm working on a marketplace app and I need to display a picture and name of a product when someone shares a link. Similar to how social media posts include a picture and title when shared. Can this be achieved using Angular, and if so, what steps do ...

Angular 4: Loading components sequentially

I am currently working with Ionic 3 and based on the Angular 4 framework. I have a question regarding loading multiple children components asynchronously, one by one: Load parent component; Load first child component; After the first child component is l ...

Access a Map URL through a native mapping application on your device

Q: I'm looking to open a specific type of link on the Native Map app. Can anyone recommend a plugin that would work for this scenario? https://www.google.com/maps?q=15405 Hebbe Ln+Au... I tried using the Capacitor Browser plugin and it worked well o ...

Shopping cart development using AngularJS with Ionic Framework

I am currently in the process of developing an online marketplace app. I have successfully implemented the shopping cart functionality, although I am unsure of how to integrate it into my Ionic/AngularJS platform. Are there any resources or solutions avail ...

Simple steps to transform the "inputs" syntax into the "@Input" property decorator

There's this code snippet that I need to modify: @Component({ selector: 'control-messages', inputs: ['controlName: control'], template: `<div *ngIf="errorMessage !== null">{{errorMessage}}</div>` }) Is the ...

Is Angular Translate susceptible to race conditions when using static files for multi-language support?

Currently utilizing angular translate with the static files loader for implementing multiple languages in my project. However, I've encountered a problem where the loading of language files sometimes takes longer than loading the actual view itself, l ...

Executing the command `subprocess.run("npx prettier --write test.ts", shell=True)` fails to work, however, the same command runs successfully when entered directly into the terminal

Here is the structure of my files: test.py test.ts I am currently trying to format the TypeScript file using a Python script, specifically running it in Command Prompt on Windows. When I execute my python script with subprocess.run("npx prettier --w ...