Anna
Anna

Reputation: 1689

Angular : passing data between components using service

I work on Angular 4, onclick of one of the 'groups' its tile should be added to the list of 'favourites' (which is an array). For this I used BehaviorSubject. I am able to display default message on my FavouriteComponent.html but when I click on newMessage() from GroupComponent.ts the value in FavouriteComponent.html is not changing it remains default message. Please guide me where I went wrong or is there any other way to achieve my requirement.

DataService.ts

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class DataService {

  private messageSource = new BehaviorSubject("default message");
  currentMessage = this.messageSource.asObservable();

  constructor() { }

  changeMessage(message: string) {
    this.messageSource.next(message)
  }

}

FavouriteComponent.ts

import { DataService } from "../data.service";
@Component({
  selector: 'app-parent',
  template: `
    {{message}}
  `
})
export class FavouriteComponent implements OnInit {

  message:string;

  constructor(private data: DataService) { }

  ngOnInit() {
    this.data.currentMessage.subscribe(message => this.message = message)
  }

}

GroupComponent.ts

import { DataService } from "../data.service";
@Component({
  selector: 'app-sibling',
  template: `
    {{message}}
    <button (click)="newMessage()">New Message</button>
  `,
  styleUrls: ['./sibling.component.css']
})
export class GroupComponent implements OnInit {

  message:string;

  constructor(private data: DataService) { }

  ngOnInit() {
    this.data.currentMessage.subscribe(message => this.message = message)
  }

  newMessage() {
    this.data.changeMessage("new title to add")
  }

}

Upvotes: 2

Views: 7346

Answers (2)

Anuradha Gunasekara
Anuradha Gunasekara

Reputation: 6983

Try this.

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class DataService {

  private messageSource = new Subject<String>();

  constructor() { }

  public getMessage(): Observable<String> {
    return this.messageSource.asObservable();
  }

  public setMessage(message: String) {
    return this.messageSource.next(message);
  }

}

export class FavouriteComponent implements OnInit {

  message:string;

  constructor(private data: DataService) { }

  ngOnInit() {
    this.data.getMessage.subscribe(message => this.message = message)
  }

}

export class GroupComponent implements OnInit {

  message:string;

  constructor(private data: DataService) { }

  ngOnInit() {
    this.data.getMessage.subscribe(message => this.message = message)
  }

  newMessage() {
    this.data.setMessage("new title to add")
  }

}

Hope This helps

Upvotes: 3

Carsten
Carsten

Reputation: 4208

Remove currentMessage and subscribe to messageSource (make it public)

Upvotes: 0

Related Questions