user11204114
user11204114

Reputation:

Using Angular Service to provide data into different component

My intention is to send data from one component to another. The user can choose between 3 different offers - the click events provide different data (in this case numbers from 1 to 3) - these data is saved in the Sender as "selectedDiv" - (following isn't working) data from "selectedDiv" shall be send to Reciever and is also to be updated when "selectedDiv" in the sending component changes.

I've already found suggestions on stackoverflow.com, but none of them worked out for me.

Summarized: The component which is supposed to send data contains a number which is to be forwarded to a different component.

My progress so far:

Service:

export class SelectedService {
  selectedDiv: number;

  changeNumber(div: number) {
    this.selectedDiv = div;
  }
}

Sender:

import { Component, OnInit } from '@angular/core';
import {SelectedService} from '../selected.service';

@Component({
  selector: 'app-wedding',
  templateUrl: './wedding.component.html',
  styleUrls: ['./wedding.component.css'],
  providers: [SelectedService]
})
export class WeddingComponent implements OnInit {

  selectedDiv: number;

  public onChoose(event): void {
    this.selectedDiv = event;
    this.selectedService.changeNumber(this.selectedDiv);

  }

  constructor(private selectedService: SelectedService) {

  }

  ngOnInit() {
  }

}

Reciever:

import { Component, OnInit } from '@angular/core';
import {SelectedService} from '../selected.service';

@Component({
  selector: 'app-contact',
  templateUrl: './contact.component.html',
  styleUrls: ['./contact.component.css'],
  providers: [SelectedService]
})
export class ContactComponent implements OnInit {

  selectedDiv: number;

  constructor(private selectedService: SelectedService) {
    this.selectedDiv = this.selectedService.selectedDiv;
  }

  ngOnInit() {
  }

}

Edit: The first approach showed following error: this.selectedService.changeNumber is not a function

Screenshot from Augury (receiving component somehow remains empty):

Sending WeddingComponent: WeddingComponent

Receiving ContactComponent: ContactComponent

Upvotes: 0

Views: 42

Answers (1)

Massimiliano Sartoretto
Massimiliano Sartoretto

Reputation: 1351

The issue is that you are providing the SelectedService directly in the components, therefore you are getting two different instances of the same class.

You have 3 solutions:

  • Register the provider in a component parent of both WeddingComponent and ContactComponent
  • Register the provider in the module containing both WeddingComponent and ContactComponent
  • Add provideIn: root as a parameter of the Injectable decorator directly in the service

Depending on the scope of the service you need to choose one option.

Upvotes: 2

Related Questions