Tips for updating an Observable array in Angular 4 using RxJS

Within the service class, I have defined a property like this:

articles: Observable<Article[]>;

This property is populated by calling the getArticles() function which uses the conventional http.get().map() approach.

Now, my query is about manually adding a new article to this array - one that has not yet been persisted and hence is not obtained through http get.

Here's the scenario: You create a new Article instance, but before saving it, I want this new object to be pushed into the Article[] array so that it appears in the list of articles.

Moreover, this service is shared between two components. If component A utilizes the service with ng OnInit() and binds the result to a repeated section using *ngFor, will updating the service array from component B automatically reflect the changes in the results displayed in component A's ngFor loop? Or do I need to update the view manually?

Thank you, Simon

Answer №1

Like you mentioned in the comments, I would opt for using a Subject.

The benefit of keeping articles observable rather than storing it as an array is that HTTP calls take time, so by subscribing, you can wait for results. Additionally, both components receive any updates.

// Simulated http
const http = {
  get: (url) => Rx.Observable.of(['article1', 'article2']) 
}

const articles = new Rx.Subject();

const fetch = () => {
  return http.get('myUrl').map(x => x).do(data => articles.next(data))
}

const add = (article) => {
  articles.take(1).subscribe(current => {
    current.push(article);
    articles.next(current);
  })
}

// Subscribe to 
articles.subscribe(console.log)

// Action
fetch().subscribe(
  add('article3')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.2/Rx.js"></script>

Answer №2

To optimize storage, it is recommended to store only the article array instead of the entire observable. You can achieve this by declaring:

articles: Article[]

fetch() {
    this.get(url).map(...).subscribe(articles => this.articles)
}

By doing this, you can easily manipulate the articles list using standard array manipulation methods.

Storing the observable would result in repeating the http call every time you subscribe to it (or use it with | async), which may not be desirable behavior.

However, if you must add items to an Observable array, you could utilize the map operator as shown below:

observable.map(previousArray => previousArray.concat(itemtToBeAdded))

Answer №3

Example from the Angular 4 book "ng-book"

Subject<Array<String>> example =  new Subject<Array<String>>();


push(newValue:String):void
{
  example.next((currentArray:String[]) : String[] => {
    return  currentArray.concat(newValue);
   })

}

In this code snippet, the example.next function is taking the current array value stored in the observable, adding a new value to it using the concat method, and then emitting the updated array value to subscribers. This functionality is achieved through a lambda expression. It's important to note that this implementation specifically works with Subject observables, as they retain the last value stored in their method subject.getValue();

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

Navigating efficiently with AngularJS directives

Hello, I am currently searching for a solution to dynamically modify the navigation links within the navigation bar based on whether a user is logged in or not. Of course, a logged-in user should have access to more pages. I have developed a UserService t ...

A guide on breaking down the ID passed from the backend into three segments using React JS

I pulled the data from the backend in this manner. https://i.stack.imgur.com/vMzRL.png However, I now require splitting this ID into three separate parts as shown here. https://i.stack.imgur.com/iy7ED.png Is there a way to achieve this using react? Bel ...

Struggling to get the Okta Auth0's AuthGuard to properly redirect to a specific route following a successful login request for a protected route

I have implemented Auth0 in my Angular application to authenticate users using the steps outlined below: Users visit the root page (e.g. ) and click on the Login button via their Google account. Users are redirected to the Auth0 login page through the Goo ...

The consistent failure of the 201 status node express API is causing major

I am currently working on creating an API using Express. However, when I receive a response from the server, it shows '201 created'. The issue arises when I attempt to make an HTTP request through promises and encounter a false interpretation of ...

Exploring MongoDB through proxyquire

To simulate a MongoDB dependency using proxyquire in my testing scenario, I have the following code snippet: var proxyquire = require('proxyquire'); var controller = path.resolve('.path/to/controller/file.js'); inside the before each ...

What is the best way to ensure that my $.ajax POST call works seamlessly with SSL?

Below is the JavaScript code I am using: parameter = "name=" + name + "&email=" + email + "&phone=" + phone + "&comments=" + comments; $.ajax({ url: 'sendEmail.php?' + parameter, success: ...

An error is thrown when attempting to use npm install, stating "integrity checksum failed. The expected sha1 checksum was sha1-6G...=, but the actual checksum was sha512

I have been browsing through various posts on different platforms trying to solve my issue, but unfortunately, I haven't had any luck. Despite having no prior experience with Angular, I was tasked with installing npm and running an unfamiliar Angular ...

How do you implement a conditional radio button in Angular 2?

I am facing an issue with two radio buttons functionality. When the first radio button is selected and the user clicks a button, the display should be set to false. On the other hand, when the second radio button is chosen and the button is clicked, ' ...

Next JS restricts XLSX to return only 100 objects as an array of arrays

I've developed a file upload system that reads Excel files and uploads data to a database (using Mongoose). After implementing the code, I noticed that when I use console.log(sheetData), it returns an array of arrays with objects inside. Each internal ...

Do you typically define a static variable within a function using `this.temp`?

I am looking to implement a static variable within a function that meets the following criteria: It maintains its value across multiple calls to the function It is only accessible within the scope of that function Below is a basic example of how I am mee ...

Create a custom JavaScript library by incorporating an external library into it as a bundle

As I work on developing a library, one of the dependencies I plan to use is fabricjs. Installing fabricjs involves specific libraries and versions that can be cumbersome for users. Despite successfully installing it in my project and using it, my concern l ...

Unlocking the potential: passing designated text values with Javascript

In my current React code, I am retrieving the value from cookies like this: initialTrafficSource: Cookies.get("initialTrafficSource") || null, Mapping for API const body = {Source: formValue.initialTrafficSource} Desired Output: utmcsr=(direct)|utmcmd=(n ...

The Jquery .clone() function presents issues in Internet Explorer and Chrome browsers, failing to perform as expected

I need to duplicate an HTML control and then add it to another control. Here is the code I have written: ko.bindingHandlers.multiFileUpload = { init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { va ...

Harnessing the Power of NextJS Image Component and @svgr/webpack for Seamless Integration

I have recently set up a Next.js site utilizing the @svgr/webpack library. In order to start using an SVG image with the new next/image component, I configured my next.config.js file accordingly. My next.config.js setup looks like this: module.exports = { ...

What is the best way to focus the video on its center while simultaneously cropping the edges to keep it in its original position and size?

I'm trying to create a special design element: a muted video that zooms in when the mouse hovers over it, but remains the same size as it is clipped at the edges. It would be even more impressive if the video could zoom in towards the point where the ...

Is there a way to include all images from a local/server directory into an array and then utilize that array variable in a different file?

I'm currently using Netbeans version 8.0.1 with PHP version 5.3 Here is a PHP file example: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/199 ...

Struggling to retrieve posted data using Angular with asp.net

I have encountered an issue while sending a post request from Angular to my ASP.NET server. I am trying to access the values of my custom model class (SchoolModel) and I can see that all the values are correct inside Angular. However, when I attempt to ret ...

I am experiencing some issues with the functionality of the Bootstrap carousel on my website's homepage

I've been working on creating an image carousel with Bootstrap 4, but I'm running into some issues. The images aren't sliding properly, and the cursor to change slides isn't functioning correctly. Additionally, the slides seem to repeat ...

Utilizing React JS to call a static function within another static function when an HTML button is clicked

Can you please analyze the following code snippet: var ResultComponent = React.createClass({ getInitialState: function () { // … Some initial state setup ……. }, handleClick: function(event) { // … Handling click event logic …… // Including ...

Retrieve the HTML data and save it as page.html, displayed in a VueJS preview

After developing an innovative VueJS-based application for managing front-end content, I am now eager to enhance it with a 'download' button feature. This new functionality will allow users to easily download the previewed and edited content in H ...