0

estoy creando un servicio en angular para setear una variable en un componente para luego obtenerla en otro componente pero ésta no se guarda dentro del servicio, cuando la voy a setear aparece "undefined", la variable la seteo y la obtengo mediante funciones get y set

---------------------servicio-------------------------------------
import { Injectable } from '@angular/core';
import { tempFirebaseRepo } from './../../Repository/tempFirebase'
import { AngularFirestore, AngularFirestoreCollection } from 
'@angular/fire/firestore';

 import 'rxjs/add/operator/map';


 import {Dispositivo} from './../../models/Dispositivo';
 import {Observable} from 'rxjs';


 @Injectable({
 providedIn: 'root'
 })
 export class tempFirebaseService {
 dispositivoRef:AngularFirestoreCollection<Dispositivo>;
 ultimoDia: Observable<Dispositivo[]>;

 private dateBefore:Date;
 private dateAfter:Date;


 constructor(private afs:AngularFirestore, private 
 _tempFirebaseRepo:tempFirebaseRepo){}

 setdateBefore(date:Date):void{
    this.dateBefore=date
    debugger
}

setdateAfter(date:Date):void{
    this.dateAfter=date
}

getdateBefore():Date{
    //let dateBefore=this.dateBefore
    //this.dateBefore=null
    debugger
    return this.dateBefore
}

getdateAfter():Date{
    let dateAfter= this.dateAfter
    this.dateAfter=null
    return dateAfter
}
 -----componente para setear la variable----------
    import { Component, OnInit} from '@angular/core';
    import {TemperaturaService} from '../../../../../../services/Temperatura/Temperatura.service';
    import {tempFirebaseService} from '../../../../../../services/tempFirebase/temp-firebase.service';
    import { DeviceDetectorService } from 'ngx-device-detector';
    import {tempFirebaseRepo} from '../../../../../../Repository/tempFirebase';

    @Component({
      selector: 'app-grafica',
      templateUrl: './grafica.component.html',
      styleUrls: ['./grafica.component.css'],
      providers: [TemperaturaService, tempFirebaseService ]
    })

     public date=new Date();
     public dateAfter=new Date(); 

   constructor(
private _tempFirebaseService: tempFirebaseService,
private _tempFirebaseRepo:tempFirebaseRepo,
private deviceService: DeviceDetectorService
) {this.epicFunction();}

 ngOnInit() {
    //this.DefaultDate();
    this.dayOfMonth = this.date.getDate();
    this.date.setDate(this.dayOfMonth - 1);
    this._tempFirebaseService.setdateBefore(this.date)
    debugger
    console.log(this._tempFirebaseService.getdateBefore())
    //this._tempFirebaseService.dateAfter=this.dateAfter;
    this.getqueryDefault();

  }
   ------------componente para obtener la variable-------
      import { Component, OnInit } from '@angular/core';
      import {tempFirebaseService} from '../../../../../services/tempFirebase/temp-firebase.service';

      @Component({
        selector: 'app-informe-mes',
        templateUrl: './informe-mes.component.html',
        styleUrls: ['./informe-mes.component.css']
      })
      export class InformeMesComponent {
        public dateBefore:Date;
        public dateAfter:Date;

        constructor(public _tempFirebaseService:tempFirebaseService){}

        ngOnInit() {
          debugger
          this.dateBefore=this._tempFirebaseService.getdateBefore()
          this.dateAfter=this._tempFirebaseService.getdateAfter()
          console.log(this.dateAfter)
        }

        public downloadPDF(){
          return xepOnline.Formatter.Format('content', {render:'download'});
        }

      }

1 respuesta 1

0

te contesto aqui porque aun no puedo comentar. Creo que es un problema de tiempos de inicio de los componentes. ES posible que estes intentando coger (getDate) antes de que que se esté informando (setDate). Te recomiendo que uses observables de forma que una vez que se haga el setDate, automáticamente te llega al componente que recoge la fecha, mediante la suscripción a ese observable.

en el servicio

import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class tuServicio {
private date: BehaviorSubject<Date> = new BehaviorSubject(null);

constructor() {}

setDate(date: Date) {
      this.date.next(date);
 }
getDate(): Observable<Boolean> {
      return this.date.asObservable();
}

en el componente que seteas la fecha llamas a setDate, tal cual venias haciendo.

Despues en el componente donde recuperas la fecha te subscribes al observable

this.DateService.getDate().subscribe( date => this.date = date)

No olvides hacer unsusbcribe en el ngDestroy para liberar memoria.

6
  • noo, yo primero seteo la variable en un componente y luego en otro la obtengo el 20 ene. 2019 a las 14:12
  • ....pero si pongo "Observable<Date>" me aparece un error donde seteo la variable: [ts] Argument of type 'Observable<Date>' is not assignable to parameter of type 'Date'. Type 'Observable<Date>' is missing the following properties from type 'Date': toDateString, toTimeString, toLocaleDateString, toLocaleTimeString, and 37 more. [2345] el 20 ene. 2019 a las 14:32
  • he detallado la respuesta, a ver si asi te sale. un saludo el 20 ene. 2019 a las 18:41
  • me aparece un error en esta linea en el componente donde obtengo la variable: this.dateBefore=this._tempFirebaseService.getdateBefore().subscribe( date => this.date = date) el 20 ene. 2019 a las 21:04
  • ts] Type 'Subscription' is missing the following properties from type 'BehaviorSubject<Date>': _value, value, _subscribe, getValue, and 21 more. [2740] el 20 ene. 2019 a las 21:04

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.