Updating a subscribed observable does not occur when pushing or nexting a value from an observable subject

Help needed! I've created a simple example that should be working, but unfortunately it's not :( My onClick() function doesn't seem to trigger the console.log as expected. Can someone help me figure out what I'm doing wrong?

@Component({
    templateUrl: 'sandbox.template.html'
})
export class SandBoxPage implements OnInit {

    dataSubject: Subject<string> = Subject.create();
    data$: Observable<string>;

    constructor(private platform: Platform) {
        this.data$ = this.dataSubject
            .asObservable()
            .startWith("First value in the observable");
    }

    onClick() {
        console.log("onClick()");
        this.dataSubject.next(Date.now + " value");
    }

    ngOnInit() {
        console.log("ngOnInit()");
        this.data$.subscribe((v) => {
            console.log("new value", v);
        }, (err) => {
            console.log("Error", err);
        });
    }
}

I've attached a button to the onClick(), but for some reason, the console.log inside my subscribe method is not getting called. It only displays once with the initial value set by startsWith.

Answer №1

When creating a subject using the create method, it's important to include the observer and observable parameters as specified in the documentation.

Rx.Subject.create(observer, observable)

More information can be found here: https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/subjects/subject.md#rxsubjectcreateobserver-observable

A straightforward solution is to simply use the new keyword when creating the subject:

dataSubject: Subject<string> = new Subject<string>();

For more details, visit: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

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

The conundrum of Content-Type in Angular 8's HttpClient Post request

Seeking assistance with POST request to backend API! I'm encountering a 415 status code due to the content-type being sent as "text/plain" when the endpoint expects application/json. Interestingly, the POST works in PostMan (see screenshot below). I ...

Ways to boost performance in an Angular 6.0 application

https://i.stack.imgur.com/Rq9Y2.jpg We have recently developed a cutting-edge application using Angular 6, hosted on an Apache 2.4 server. To ensure our website is properly crawled by search engines, we set up a local "prerender" instance. Initially, we t ...

Learn how to send or submit data using the Form.io form builder

I am currently working on a dynamic drag and drop form builder, and I'm struggling to figure out how to log the data from the form. Below is the component.html file where I am implementing the drag and drop form: <div> <form-builder ...

My HTML grid table is not being properly rendered by the JSON data

I'm currently facing a challenge with rendering my HTML grid table in Angular using JSON data retrieved from a MySQL database. I would greatly appreciate any assistance or guidance on how to solve this issue. View the output of the Angular code here ...

By implementing a custom function within the router's "redirectTo" method, we can dynamically determine the destination for redirection, effectively avoiding Ahead-of-Time (A

By implementing a function to decide where the user should be directed when the site loads, I encounter the following challenge: { path : '', redirectTo: redirector(), pathMatch: 'full' } The redirector() function returns a rout ...

Execute a chain of consecutive HTTP requests and receive an Observable in response

I am currently working on two observable request functions that need to run sequentially in order for the desired outcome. Although it is functioning, I am facing an issue where the print function needs to be executed after the newOrder api call and return ...

What is the best way to reference a component variable property within its template without explicitly stating the variable name?

Suppose my component is managing an instance of the following class: class Person { firstName: string; lastName: string; age: number; } Is there a way to directly reference its properties in the template like this: <p>{{firstName}}</p> & ...

Directing non-www to www in Next.js has never been easier

Based on the information I've gathered, it seems that using www is more effective than not using it. I am interested in redirecting all non-www requests to www. I am considering adding this functionality either in the next.config.js file or, if that& ...

Sorry, I can't do that task as it involves paraphrasing content that is already provided to me. How about I summarize the text instead?

I encountered an error while attempting to fetch data from an API for my Ionic 5 application. I attempted removing all the arrays but unfortunately, it did not resolve the issue. Can someone please provide assistance? Below are the files being used: type ...

Typescript raises an error when providing a potentially null value (that is not null) to an unnamed callback function

When dealing with a property that starts as null, how can I pass it to an anonymous callback function expecting a non-null value without TypeScript throwing errors? I've tried wrapping the function call in an if statement to check for null at the cal ...

Leveraging the Recyclability Aspect of a ReactJS Modal

Looking for a way to make a modal dynamic without duplicating too much code. Any suggestions on how to achieve this? I've managed to separate the state from the layout using render props. interface State { open: boolean; } interface InjectedMod ...

Is it possible to categorize a JSON object based on its properties and then count the occurrences of each property within

I have an array of objects containing booking information and I need to calculate the count of each booking item in every object. const arr = [ { "ID" : 1, "Name":"ABC", "Bookings":[ { & ...

Is there a way to display a PowerPoint presentation preview within an Angular application without utilizing the ngx-doc-viewer plugin?

Is it possible to display a PowerPoint preview in an Angular application? I am looking to show PowerPoint presentations stored in a server location. I prefer not to use ngx-doc-viewer as it appends "https://docs.google.com/gview+fileurl" instead of just " ...

Enhance the functionality of angular-material buttons by incorporating dynamic loading animations into

I am currently working on a solution in Angular 12 to disable a button (and show a spinner) when it is clicked, until the API responds. To achieve this, I plan to follow a similar approach to the angular-material button implementation. Essentially, I want ...

Is there a simple method I can use to transition my current react.js project to typescript?

I am currently working on a project using react.js and am considering converting it to typescript. I attempted following an article on how to make this conversion but have run into numerous bugs and issues. Is there a simpler method for doing this conver ...

How can I populate separate lists with data from an Angular GET request response?

I am new to using Angular and I have been struggling to build a frontend application that can consume my REST API created with Django. Despite searching for two days, I have not found a satisfactory answer to my problem. Chat GPT also seems to be inaccessi ...

What is the best way to save code snippets in Strapi for easy integration with SSG NextJS?

While I realize this may not be the typical scenario, please listen to my situation: I am using Strapi and creating components and collections. One of these collections needs to include code snippets (specifically typescript) that I have stored in a GitH ...

Oops! It seems like there is an issue with the Renderer2 provider in Angular v 4.1.3

Currently in the process of refactoring one of my services due to a breakage post-upgrade. I had to replace browserdomadapter(); along with several other deprecated methods. As a result of multiple deprecations starting around version 2.1 and various brea ...

Solving Angular2 Dependency Issues

I'm curious about Angular 2 and whether there's a way to resolve dependencies without having to use the constructor. In .NET, you can inject dependencies in three ways (constructor, setter, interface-based). Is it possible to do setter injection ...

Angular routing is failing to redirect properly

After creating a sample Angular app, the goal is to be redirected to another page using the browser URL http://localhost:1800/demo. The index.html file looks like this: <!doctype html> <html lang="en"> <head> <title>Sample Ang ...