Join the Observable in Angular2 Newsletter for the latest updates and tips

One of my functions stores the previous URL address.

   prevId () {
     let name, id, lat, lng;
    this.router.events
      .filter(event => event instanceof NavigationEnd)
      .subscribe(e => {
        console.log('prev:', this.previousUrl);
        this.previousUrl = (e as NavigationEnd).url;
    }

I've been attempting to rewrite this in an Observable-style format, but so far, nothing I try seems to work. Is there a way to make it possible? Also, can you recommend any good articles on Observables since I am new to this concept and it appears quite complex to me?

UPDATE: I need to access the data outside the function later on, hence the reason why I require an Observer.

For example:

myFun(a) {
console.log(a);
}

myFun(this.previousUrl);

Answer №1

If you only require the URL outside of your function, you can achieve this by:

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/take';

getPreviousUrl(): Observable<NavigationEnd> {
  return new Observable(observer => {
    this.router.events
      .filter(event => event instanceof NavigationEnd)
      .take(1)
      .subscribe(e => {
        observer.next(e as NavigationEnd);
        observer.complete();
      });
  });
}

To use the function, follow this format:

getPreviousUrl().subscribe(navigationEndEvent => {
  this.previousUrl = navigationEndEvent.url;
});

This example assumes that you only need the previousUrl information when calling getPreviousUrl(). Hence, I included the .take(1) operator and called observer.complete().
The .take(1) automatically unsubscribes the subscription created in this.router.event after receiving the first value.
Additionally, observer.complete() will unsubscribe all subscriptions made within the returned Observable.

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

Issue with Nuxt2 CompositionAPI: Unable to showcase imported render function in component - Error message states "template or render function not defined"

I have created a render function that I believe is valid. I am importing it into a component and registering it within the defineComponent. However, when running the code, I encounter an error saying "template or render function not defined". I am confide ...

Why isn't my state being updated properly with React's useEffect, useState, setInterval, and setTimeout functions?

const handleClick = () => { if (!activated) { if (inputValue == '') { return } if (!isNodeInGraph(graph, inputValue)) { return } } setActiv ...

How to send information to a modal component in ReactJS?

I'm feeling a bit lost here, maybe I'm missing something. What I am trying to achieve is a loop that populates an array with progress bar elements and then displays them with the relevant information. When a user clicks on a progress bar, the d ...

Angular: Modifying a Component Property Value within an ngFor Loop

Within an ngFor loop, I have a tabs component. To apply a CSS class, I utilize the boolean property show, which is initially set to false. When I click on the component, the value of show toggles to true. However, if I click on another component, I need to ...

A dynamic substitute for the Supersized slideshow option

I am in the process of updating my website and the final task on my to-do list is to replace the Supersized plugin with a more suitable alternative. The website is constructed using WordPress and I am utilizing jQuery. My goal is to find a fullscreen slid ...

Managing the layout with React Native Flexbox to evenly distribute items

Check out this React Native Demo I put together featuring Santa images being added and removed in a Flexbox. Bunch of Santas I noticed that when there are more than 3 Santas, the layout shifts to the left. I'm curious about how to keep the Santas ce ...

Error message: "Uncaught TypeError in NextJS caused by issues with UseStates and Array

For quite some time now, I've been facing an issue while attempting to map an array in my NextJS project. The particular error that keeps popping up is: ⨯ src\app\delivery\cart\page.tsx (30:9) @ map ⨯ TypeError: Cannot read pr ...

What strategies prove most successful in resetting a reactive angular form effectively?

I'm currently working with Reactive Forms using Angular Material inputs (mdInput) that are initialized with FormBuilder in the following way: contactForm: FormGroup; this.contactForm = this.fb.group({ name: ['', [Validators.required, Val ...

Tips for transferring the value of ng-model to multiple controllers

Is it possible to access the value of an ng-model from two different controllers? While I am aware that using a service is one way to share data between controllers, I am struggling to figure out how to pass the value of an ng-model to a service for this ...

Validating dropdown lists with Jquery

Custom Dropdownlist: <div class="col-md-2"> <div class="form-group"> <label for="field-3" class="control-label">Priority</label> <select id="lstpriority" class="custom-selectpicker" data-live-search="true" da ...

What is the best way to retrieve JavaScript variable data from a GDownloadUrl callback function?

Recently, I attempted to extract data by crawling a website. The website in question offers real-time information on bicycle stations through Google Maps. GDownloadUrl("/mapAction.do?process=statusMapView", function(data, responseCode) { var jso ...

I am facing an issue where using JSON stringify in React Native successfully returns my array, but it is unable to display

Every time I input {alert(JSON.stringify(cart[0]))} in my react-native application, the result displayed is the complete array of objects as shown below: [{ "id": 3, "name": John, . . }] However, when I try {alert(JSON.stringif ...

Get all Facebook friends that can be tagged using Angular

Seeking to access all taggable Facebook friends of a user. As Facebook only shows 25 friends at once, I aim to include a button for loading the next set of users. (I understand that I could increase the limit, but sticking to 25 per request is more effici ...

Keycloak does not support using the updateToken() function within an asynchronous function

In our development of a Spring application with React/Redux frontend, we faced an issue with Keycloak authentication service. The problem arose when the access token expired and caused unexpected behavior in our restMiddleware setup. Here is a simplified v ...

Why are the UI components (`Card Number`, `MM/YY`, `CVC`) not being displayed in the React app when using Card

Having an issue where the CardElement Ui component is not visible in the image provided. It should appear above the Order Total: $0 next to the payment method. https://i.sstatic.net/NCK5z.png I've attempted various debugging methods without success. ...

Deactivate debugging data for Tensorflow JS

Is there a way to turn off all debugging logs in Tensorflow JS similar to what can be done in Python with setting an environment variable and calling a function? Disable Debugging in Tensorflow (Python) According to the top answer: import os os.environ[ ...

Chrome is experiencing a rendering problem as a result of using @Font-Face

Having trouble with rendering in my Angular 4 application, similar to the issue outlined in this post about Angular 2 Chrome DOM rendering problems. Despite there being a solution provided in that post, I am still facing difficulties when navigating betwee ...

Tips for displaying HTML content using an array in Vue JS

Hi, I'm a beginner with Vue JS and I'm working on passing an HTML table using this array. I have a dropdown where I can select the option I want, but I'm struggling to figure out how to include HTML within it. Whenever I try, it ends up disp ...

Move the cache folder for NextJS to a new location

Is it possible to customize the location of the cache folder currently located in "./.next/cache"? I am interested in modifying this because I am developing an application that receives high traffic daily, and I plan to deploy multiple applications from m ...

Getting the percentage of code coverage in Selenium tests in relation to the web application code

I need to track the code coverage of my selenium tests in relation to the source code of the server (web application source code) that they cover. For instance, I want the tests for the login feature to measure how much of the web application's code ...