Search code examples
javascriptangulartypescriptgetter-setter

angular2 sharing data between components , getters and setters


I have a question identical to this guy here:

Angular 2 Setter and Getter

The solution que provided thought is not enough for my project to work so I'll explain my situation with some more details to see if you guys can help me!

I have a service dataBase.service.ts :

import {Injectable} from "@angular/core";

@Injectable()
export class dataBaseService{

    serviceData: string;

    get data():string{
        return this.serviceData;
    }

    set data(value:string){
        this.serviceData = value;
    }
}

this service is obviously added to app.module.ts as a provider..

on my component A i have:

import { Component, OnInit } from '@angular/core';
import {dataBaseService} from "../dataBase.service";




@Component({
  selector: 'app-tipo',
  templateUrl: './tipo.component.html',
  styleUrls: ['./tipo.component.scss'],
    providers: [dataBaseService]
})
export class A implements OnInit {


  constructor( public dataService:dataBaseService) {
      this.dataService.serviceData = 'hello';
  }



  ngOnInit() {
      console.log(this.dataService.serviceData);
  }

}

Until Here everything is fine. If I show on console:

console.log(this.dataService.serviceData); it returns me "hello" as expected

but on my next component when I print again the same data it shows undefinied:

import { Component, OnInit } from '@angular/core';
import {dataBaseService} from "../dataBase.service";

@Component({
  selector: 'app-modelo',
  templateUrl: './modelo.component.html',
  styleUrls: ['./modelo.component.scss'],
    providers: [dataBaseService]
})
export class ModeloComponent implements OnInit {



  ngOnInit() {
      console.log(this.dataService.serviceData);      
  }
    constructor(public dataService: dataBaseService) {

    }

}

console.log(this.dataService.serviceData); it returns "undefined".. So how can I save that data that I putted on the first component and beeing able to show it on another component? what am I missing?

UPDATE:

Some people like me didn't find an answer to the other question like this one on stack and that's because Instead of adding the providers individually you have to add them globably (on module.ts) !!!!!!!!!!!!


Solution

  • As you said you have already added the provider on the module level,try commenting out the providers declaration from components.