Angular2 - The Art of Subscribing to Service Members

Okay, so I'm aware that this question has been asked multiple times - I've gone through various answers and documentation, but for some reason, I can't seem to get it to work. I just want to confirm that I haven't missed anything.

The scenario is as follows: Two Components, One Service. Both Components need to interact with the Service, with one Component needing to respond when a member of the Service changes.

I have a service with a BehaviorSubject containing a domain object

@Injectable()
export class MyService {

    addedMyObject:Subject<MyObject> = new BehaviorSubject();

    constructor(private http:Http) {}

    getAndAddMyObject(objectId:string) {
        this.getMyObject(objectId) // assume this method exists
            .subscribe((o) => {
                this.addedMyObject.next(o);
            });
    }
}

I have one component listening for changes on the Service's BehaviorSubject

export class MyFirstComponent() implements OnInit {

constructor(private myService : MyService) {}

    ngOnInit() : void {
        this.myService.addedMyObject
                .subscribe((o) => {
                    console.log("Incoming object, add to a list or something");
                })
    }
}

Then, there's a second component that calls the Service to make changes

export class MySecondComponent() {

    constructor(private myService : MyService) {}

    addSelectedObjectToSomething(objectId) {
        this.myService.getAndAddMyObject(objectId);
    }
}

However, strangely enough, the subscription in MyFirstComponent isn't triggering. It's really puzzling. What could be the issue?

Answer №1

Your code seems to have some typos that are causing errors, making it difficult for me to give you precise suggestions on what needs fixing. However, I tested a similar version locally and it worked smoothly:

Service:

@Injectable()
export class MyDataService {

    myDataSubject = new BehaviorSubject<any>(null);

    fetchDataAndAddToObservable(dataId: string) {
        this.fetchData(dataId).subscribe(d => {
            this.myDataSubject.next(d);
        });
    }

    fetchData(id: string): Observable<any> {
        return Observable.of({key: 'value'});
    }
}

Component 1:

@Component({
    selector: 'first-component',
    template: `
        Hello
    `,
})
export class FirstDataComponent implements OnInit {

    constructor(private dataService: MyDataService) {}

    ngOnInit(): void {
        this.dataService.myDataSubject.subscribe(d => {
            console.log("Received data - process accordingly", d);
        })
    }
}

Component 2:

@Component({
    selector: 'second-component',
    template: `
        <button (click)="addDataToCollection(1)">Add</button>
    `,
})
export class SecondDataComponent {

    constructor(private dataService: MyDataService) {}

    addDataToCollection(dataId) {
        this.dataService.fetchDataAndAddToObservable(dataId);
    }
}

Upon clicking the button in the second component, I observed the correct data being logged successfully.

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 function cloneElement does not share any properties with the type Partial<P> and Attributes

I'm encountering a perplexing issue with my code. When I attempt to call cloneElement with the second parameter being of type Type { foo: number } has no properties in common with type 'Partial<Child> & Attributes', TypeScript thro ...

The element does not recognize the property 'width' since it is not defined in the type of 'GlobalEventHandlers'

I'm trying to determine the size of an image using JavaScript, but I encountered a TypeScript error: const img = new Image(); img.onload = function() { alert(this.width + 'x' + this.height); } img.src = 'http://www.google.com/intl/en_ ...

Setting angular variables by assigning form values

My current reactive form setup looks like this: this.editform = new FormGroup({ 'username' : new FormControl(null,[Validators.required]), 'password' : new FormControl(null,[Validators.required]), 'full_name' : ne ...

Compiling Typescript has no effect

As I work on developing a REST API using Express in Typescript, I have encountered a perplexing issue with the Typescript Compiler. When I compile the project locally on my Windows 10 machine using tsc -b, everything goes smoothly. However, when I attempt ...

Transferring data from an Angular 2 component to a service

I am trying to pass data from an Angular component to a service and utilize the service's methods to manipulate it. Here is an example: class SomeComponent { public info: Array<any> = MyData; constructor(private myService: TablePag ...

Create a Typescript index signature that incorporates individual generic types for each field

Many times, the keys of a record determine its value. For instance: const record = { [2]: 5, ["string"]: "otherString", ["there is"]: "a pattern" } In these instances, each key of type K corresponds to the ...

Updating select options list dynamically in Angular

In a modal, I have two selects that are populated with data from two different object arrays: <select class="browser-default" id="gebied" [(ngModel)]="filteredGebied" (ngModelChange)="onChange($event)"> <option *ngFor="let gebied of lis ...

Can you explain the significance of the `?` symbol before an object attribute? And why is my TypeScript file not recognizing it?

I have always utilized this particular behavior in Angular using the *ngIf directive when dealing with an object that could potentially be undefined or not the required object. <div *ngIf="object?.foo"> ... </div> Although I know that this ...

What is the procedure for utilizing the Type Checker to obtain an Interface or Class that extends a

Here is an example code snippet: class Animal { name: string; } class Dog extends Animal { breed: string; } interface DataProps { color?: string; } interface DogProps extends DataProps { type?: "Beagle" | "Sheepdog"; } When using Cla ...

Guide on dynamically injecting a helper class

Within my component, I am utilizing two different helper classes as shown below: import {HelperA} ... import {HelperB} ... ... @Component({..}) export class MyComponent implements OnInit { helper: Helper; constructor(private ref: ElementRef, ...

Issue: Unable to load the file named 'script.ts' while employing chrome.scripting.executeScript

Currently, I am working on developing a chrome extension using Vite with React and Typescript along with CRXJS. This is my initial project in this domain. The issue I am encountering is related to executing a script on the current tab when a button is clic ...

What is the best way to go about reading the .txt file and executing the query to add the records?

I have a .txt file containing an insert query with around 10,000 records. Below is an example: INSERT INTO tblVeiculo (VeiculoId, Codigo, Fabricante, Modelo, AnoInicial, AnoFinal, Portas, Combustivel, NrMotorObstruido) VALUES (1, '001034066', &a ...

Create a versatile generic object using TypeScript

Looking to create a versatile onFilterChange helper function that works for all filters, eliminating the need to write it out separately each time. However, I've hit a snag: // helper.ts export function onFilterChange(prevState: Record<string, any& ...

Exploring Restricted Methods in Angular Classes

Is it possible to access protected properties of an Angular Library Class from within an Angular app? Specifically, I am trying to retrieve the value stored in a protected property _gridInterval from the Class "DateAxes" of the amChart4 library However, ...

Explore Visual Studio Code's feature to debug Node.js applications written in TypeScript

I'm currently facing an issue while debugging a Node JS application written in TypeScript using Visual Studio Code. The problem is similar to the one discussed in this question |-- .settings |----- launch.json |-- bin |----- app.js |----- app.js.map ...

Having trouble with Typescript in React and Firestore? Wondering why you are receiving the error message "Variable 'l' implicitly has type 'any[]' in some locations where its type cannot be determined.ts"?

For my To Do List project, I am utilizing Next.js/React with Firebase as the backend. The task items consist of name, time required for task completion, and due date fields. My goal is to retrieve the items from the Firebase collection and set them in setD ...

swap the keys and values of a record type in a literal form

How can I reverse the keys and values of a record literal in typescript? For example: type Foo = { x: "a", y: "b", z: "c" }; I want to create a type Flip<X> where: type Bar = Flip<Foo>; // should result in { a: & ...

Using the `window` object in Jasmine with Angular, a mock can be created for testing purposes

In my current project, I have a function that I need to write unit tests for. Within this function, I am comparing the global objects window and parent using const isEqual = (window === parent). I am wondering what would be the most effective way to mock ...

Add a new child component template with each click using the onclick event in Angular

Is there a way to dynamically add a child component with each button click event? Here is the HTML code for the button: <button type="button" class="btn btn-success btn-sm btn-add-phone" (click)="addfield()"><span class="fa fa-plus"></span ...

Expanding the capability of a function by inheriting properties of either type any or unknown

Can you explain why the values of P1 and P2 are different in these type definitions? type P1 = (() => 22) extends {[k:string]:any} ? 1:2 //`P1 == 1` type P2 = (() => 22) extends {[k:string]:unknown} ? 1:2 //`P2 == 2` ...