2

i created sharedService it works perfectly , i can shared data from one component to another (this both are irrelevant component in different module).

  • Data Transfer as follows:

AdminDashboard.Component (update value) ===> conference.component (get new updated value)

problem : when i refresh my conference.component i lost the value

EventService.ts

import { Injectable } from '@angular/core';
import { Observable, BehaviorSubject } from 'rxjs';
import { importExpr } from '@angular/compiler/src/output/output_ast';
import {Events} from '../models/event.model'


@Injectable()
export class EventService {
    private dataSource = new BehaviorSubject(null);
    sendMessage(data) {
        this.dataSource.next(data);
    }

    getMessage(): Observable<any> {
        return this.dataSource.asObservable();
    }
}

dashboard.component (url /dashboard)

on Button Click msg() method called , which updated BehaviourSubjectvalue.

import { Component, OnInit} from '@angular/core';
import { NgForm } from '@angular/forms';
import { EventService } from '../../shared/sharedServies/eventService.service';

export class AdminDashboardComponent implements OnInit {
 constructor( private testEventService: EventService){ }
  msg() {
    debugger
    this.testEventService.sendMessage('Message from Home Component to App 
    Component!');
  }
}

conference.component (url /conference) Here , i hold value in message and bind to ui.

import { Component, OnInit } from '@angular/core';
import { EventService } from'../../shared/sharedServies/eventService.service';
import { Subscription } from 'rxjs/Subscription';

export class ViewconferenceComponent implements OnInit {
    message: any;
    constructor(private EventService: EventService) {
        this.subscription = this.EventService.getMessage().subscribe(message => {
            console.log(message)
            this.message = message;
        });
    }

}

Question :

  • when i get data on /conference page , at this when i refresh the service holded value is lost , i didn't understand what this happens.

  • also i need to add json to sharedService , how it will achive?

Bhagvat Lande
  • 1,392
  • 3
  • 17
  • 34

1 Answers1

0

This is expected since when you "switch" components they are destroyed. You could work around this quickly by adding state variables to your service.

Personally, I encourage you to make use of some state library like ngRx https://github.com/ngrx/platform