F. K.
F. K.

Reputation: 964

Singleton Service in Angular 9 not working

I am using a singleton service to store shared data. Code for the service is below:

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

@Injectable({
  providedIn: 'root'
})
export class UploadedFileService {
  private upLoadedFile: File;
  constructor() { }
  public setUploadedFile(file: File) : void {
    this.upLoadedFile = file;
  }
  public getUploadedFile(): File {
    return this.upLoadedFile;
  }
}

In the class below, I am setting the upLoadedFile. Code is below:

import { Component, OnInit } from '@angular/core';
import { UploadedFileService } from '../uploaded-file.service';
import {Router} from '@angular/router';

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

  constructor(private uploadedFileService: UploadedFileService, private router: Router) { }

  ngOnInit() {
  }
  files: any = [];
  file: File;

  private emptyArray() {
    this.files.splice(0, this.files.length);
  }

  uploadFile(event) {
    this.emptyArray();
    for (let index = 0; index < event.length; index++) {
      const element = event[index];
      if(element instanceof File) {
      this.files.push(element.name);
      this.file = element;
      }
  }
  this.uploadedFileService.setUploadedFile(this.file); 
  this.router.navigate(['preview'])
}
}

When I try to access the upLoadedFile in my preview component (code below), I get undefined:

import {Component, Input, ViewEncapsulation, OnInit} from '@angular/core';
import {read, utils} from 'xlsx';
import {FileUtilsService} from '../file-utils.service';
import { UploadedFileService } from '../uploaded-file.service';

@Component({
  selector: 'app-preview-file',
  templateUrl: './preview-file.component.html',
  styleUrls: ['./preview-file.component.css'],
  providers: [FileUtilsService, UploadedFileService]
})
export class PreviewFileComponent implements OnInit{
  uploadedFile: File;
  constructor(private fileUtilService: FileUtilsService, private uploadedFileService: UploadedFileService) {
  }
  ngOnInit() {
  // The uploadedFileService.getUploadedFile() returns undefined
    this.uploadedFile = this.uploadedFileService.getUploadedFile();
    this.preview_file();
  }
  preview_file() {
    const reader = new FileReader();
    reader.readAsArrayBuffer(this.uploadedFile);
    reader.onload = function(e: any) {
      const data = new Uint8Array(e.target.result);
      const arr = new Array();
      for (let i = 0; i !== data.length; ++i) {
        arr[i] = String.fromCharCode(data[i]);
      }
      const bstr = arr.join('');
      const workbook = read(bstr, {type: 'binary'});
      const first_sheet_name = workbook.SheetNames[0];
      const container = document.getElementById('preview_id');
      container.innerHTML =  utils.sheet_to_html(workbook.Sheets[first_sheet_name], {});
    };
    }
  }

I tried everything. I am not sure where the issue is. The uploaded file seem to be updated in the service but when I try to get it from the service in the preview module, it always returns undefined.

Upvotes: 2

Views: 610

Answers (1)

Arun Mohan
Arun Mohan

Reputation: 1227

If you add a service in providers array then that component and all its children will get a separate instance of that service. ie, It wont be a singleton service anymore. Remove that from providers and it will work.

Upvotes: 4

Related Questions