3

I have a function that will require a seperate header component to refresh when its used.

Foo Component (needs to reload header component)

handleTimeListChange(value) {
    this.cp = value.
    localStorage.setItem('cp', this.cp);

    //reload header.component
  }

The result should be when time handleTimeListChange is used a call will reload (header.component)

Alex D
  • 788
  • 2
  • 11
  • 33

2 Answers2

1

For this problem you can use rxjs SubjectBehaviour.make random service like this

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

    @Injectable()
    export class RandomService {

      private msgsource = new BehaviorSubject<string>('this is the default');
      telecast = this.msgsource.asObservable();

      constructor() { }

      editMsg(newmsg) {
        this.msgsource.next(newmsg);
      }

    }

This component from which you want to send the data, declare that service method and and send the date to that method and where ever that service method is being called that data will reflect their.

      import { Component, OnInit, Input } from '@angular/core';
        import { RandomService } from '../random.service';

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

          @Input('incomingmsg') newrandmsg: string;

          message: string;
          editedmsg: string;

          constructor(private someserv: RandomService) { }

          ngOnInit() {
          }

          editthemsg() {
            this.someserv.editMsg(this.editedmsg);
          }

        }

now receive that data to header component in ngOnInit that will detect any value changes in that service method.

HEADER COMPONENT

ngOnInit() {
        this.someserv.telecast.subscribe(message => this.message = message);
      }

when ever any changes come under random service it will detect and show that data to header component.

Ankit
  • 66
  • 1
  • 8
0

You can use a BehaviorSubject for communicating within different components throughout the app. You can define a data sharing service containing the BehaviorSubject to which you can subscribe and emit changes.

see this ans: https://stackoverflow.com/a/46049546/4899523

Abdul Rafay
  • 3,241
  • 4
  • 25
  • 50