Tips for clearing an observable in Angular version 4

In the code snippet below, an observable has been created:

  private permissionSubject = new Subject<any>();
  permissionObservable$ = this.permissionSubject.asObservable();


  constructor( public apiService: ApiService) { }

  updatePermissionsData(permissionData){
    this.permissionSubject.next(permissionData);
  }

  getPermissions(){
    return this.apiService.get('/getUserPrivileges')
    .map(data =>  data)
  }

The purpose here is to push incoming data to the Observable every time it is received.

For instance: Let's say we have an observable -> [1, 2] and we receive a new data which is 3, the updated observable will become [1, 2, 3]

What I want to achieve is to remove the values 1 and 2 from the Observable before adding the new value 3. How can this be done?

Will Observable.empty() accomplish this, and if so, how should I modify my code?

Despite searching on stackoverflow, I couldn't find a solution to my problem, so I'm seeking help here...

Updated code

Subscribing observable

    checkPermissions() {
            this.checkPermService.permissionObservable$.subscribe(
    // The following block gets executed multiple times whenever new data is received via the observable
              data => {
                  this.saveMenuItemsOnPermissions(data)
              }
            )
          }

Answer №1

It appears that there may be a misconception about how Observables function. Your code lacks a buffer or memory structure.

Explanation of Your Code

// Creating an instance of a subject.
// Subjects do not retain memory!! The stream is only pushed to subscribers once.
private permissionSubject = new Subject<any>();

// Restricting `permissionObservable$` to listen without publishing
permissionObservable$ = this.permissionSubject.asObservable();

// Constructor instantiates the apiService
constructor(public apiService: ApiService) { }

// Each time this function is called, permissionData is pushed through
// permissionObservable and its subscribers.
updatePermissionsData(permissionData){
   this.permissionSubject.next(permissionData);
}

// Calling a service and waiting for subscription (probably an http call)
// The map function is unnecessary by the way
getPermissions(){
  return this.apiService.get('/getUserPrivileges')
  .map(data =>  data)
}

Observable.empty()

Create an Observable that emits no items but terminates normally

Observable.empty() is not a method!! It is an observable designed to:

  1. Not emit anything
  2. Pause the stream

Edit:

If you simply want to ignore the first 2 elements of an observable, you can utilize the skip operator.

Skip Operator:

Skip allows you to ignore the first x emissions from the source. Skip is typically used when an observable always emits certain values upon subscription that you want to disregard. This can be useful if the initial values are not necessary or if you are subscribing to a Replay or BehaviorSubject and do not need to take action on the initial values. Consider using skip if you are only interested in later emissions.

// The below code is executed multiple times whenever the observable receives new data (stream data)
checkPermissions() {
  this.checkPermService.permissionObservable$.skip(2)
     .subscribe(data => {
              this.saveMenuItemsOnPermissions(data)
      })
 }

Keep in mind these 2 important points:

  1. Subscription must occur before the observable starts emitting
  2. checkPermissions will ignore the first 2 elements received during subscription, but will capture all subsequent ones.

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

Is there a way to serve an HTML file using the response object in expressjs while also incorporating an external JavaScript file?

My express application successfully serves an HTML page from my disk when I initially make a GET request to "http://localhost:3000/" in the browser. Now, I am trying to access a JavaScript file that is located in the same directory on the disk as the HTML ...

Error in JSON due to the presence of an unexpected token within the

I am facing a challenge with my PHP code, where I take a list of filenames or empty strings and store them in an array. This array is then converted to JSON and saved in a database successfully. However, the problem arises when this array is also stored wi ...

Looking to incorporate ReactiveFormsModule into an Angular custom library, but hitting roadblocks

I'm currently facing an issue with integrating reactive forms in my Angular custom library development. I decided to include @angular/forms as a peerDependency in the library's package.json manually, like so: { "name": "abc-library" "version": ...

Is there a way to make AJAX post on another page?

I am facing an issue where the data I send is supposed to be echoed out on the second page, but instead it echoes out on the first page. How can I ensure that it displays on the second page and not the first? Even though the code on the second page is exe ...

Issue with Ajax form submission functionality not working for sending form data

I recently found the solution to executing a Send Mail script without reloading the page after facing some AJAX issues. However, I am now encountering a problem where the post data is not being received by the PHP script when my form posts to AJAX. For re ...

Error encountered: `TypeError: Unable to access undefined properties (specifically, '0') within the Simple React Project`

Currently in the process of learning React and working on a simple photo application. Encountering an issue: Collection.jsx:6 Uncaught TypeError: Cannot read properties of undefined (reading '0') Why is this happening? Everything was functioni ...

Is there a way for me to retrieve data from a v-for loop in VueJS with the Quasar Framework?

I am currently working on a q-markup-table code to display products based on a search query. I have successfully implemented a button that allows the user to select a row from the table, and once selected, the row data is sent to an array named "selected ...

Carousel with Bootstrap: Heading positioned over the content

My goal is to have the caption of Bootstrap Carousel displayed above the content, but I'm encountering issues with it. When clicking on the chevrons, you may notice the < Item 1 > bouncing... (This behavior is a bug, and logically speaking, I ex ...

Exploring jQuery Mobile | Moving Seamlessly between Pages

I'm relatively new to JQM and I'm working on creating a mobile application using jQuery Mobile. Here's the goal I'm aiming for: I have multiple HTML pages, each with its own CSS, JavaScript, and JQM components. What I want is to be ab ...

Issue with JQuery click() not triggering on a specific div button

I am attempting to replicate a user's click on a website where I have no control over the code. The specific element I am trying to interact with is a div that functions as a button. <div role="button" class="c-T-S a-b a-b-B a-b-Ma oU v2" aria-dis ...

Generate a Year attribute value using the information from the year field in a JSON document

Currently, I am exploring the functionalities showcased in this example: I am interested in adapting the following code snippet to work with my JSON file, which lacks a specific date data type field but includes a 'Year' value: // Transform Yea ...

Using Ajax and jQuery to redirect a page with values in ASP.NET

I have two pages: Default.aspx and DetailView.aspx. My goal is to redirect from Default.aspx to DetailView.aspx using an AJAX call and pass a value as well. Although I have tried something, the function defined in the class is not being called. The functi ...

What steps are involved in enabling Server Side Rendering with Next.js?

For my exploration of Next.js, I started by setting up a new Next.js project and incorporating code to retrieve weather data: export default function Home() { const [data, setData] = useState(null); useEffect(() => { fetch("https://api.we ...

The Typescript compiler is throwing an error in a JavaScript file, stating that "type aliases can only be used in a .ts file."

After transitioning a react js project to react js with typescript, I made sure to move all the code to the typescript react app and added types for every necessary library. In this process, I encountered an issue with a file called HeatLayer.js, which is ...

Enhance your data visualization with d3.js version 7 by using scaleOrdinal to effortlessly color child nodes in

Previously, I utilized the following functions in d3 v3.5 to color the child nodes the same as the parent using scaleOrdinal(). However, this functionality seems to be ineffective in d3 v7. const colorScale = d3.scaleOrdinal() .domain( [ "Parent" ...

Turn off logging functionality in a Node.JS environment

I am looking to turn off logging for specific environments in my Node.JS application using Express. Would the following method be considered the most optimal way to disable logging within Node.JS applications? if(process.env.NODE_ENV == "production") { ...

Using a function from one class within another class by passing it as a prop

Below are the methods found in my Search.tsx class. renderSuggestion(suggestion) { <div className="buttons"> <button className="button">View Location</button> <button className="button whitebutton" onClick={this.h ...

Issue with sending functions to other components in Angular

I'm currently facing an issue with passing functions to other objects in Angular. Specifically, I've developed a function generateTile(coords) that fills a tile to be used by leaflet. This function is located within a method in the MapComponent. ...

Experiencing an excessive amount of re-renders

Encountering the error of too many re-renders Attempted to utilize useEffect to render only when weather changes function DashboardHeaderContent({ looks, weather }) { const [seasonRange, setSeasonRange] = React.useState(); function renderLook(look) ...

Navigating through JSON data to retrieve specific values and executing repetitive actions

When the form is submitted, I am making an AJAX request to PHP code and this is the response I receive. var data = { "empty":{ "game_sais_no":"Season cannot contain empty value", "game_sc_no":"Category cannot contain empty value", ...