Search code examples
angularservice

Angular services don't store data


I'm trying to do app with date filter. So here's my problem:\

I want to store data in my service but when i'm routing my array at service is resetting itself.

How can i keep data permanently at my service.

Here's my code:

task.service.ts

import { Injectable } from '@angular/core';
import { NewTaskPageComponent, ToDoTask } from './new-task-page/new-task-page.component';
import { task } from './app.component';

@Injectable({
  providedIn: 'root'
})
export class TaskService {
  tasks:ToDoTask[] = [];
  constructor() { 
  }
  addTask(task:ToDoTask){
    this.tasks.push(task);
  }
  getTasks():ToDoTask[]{
    return this.tasks;
  }

}

new-task-page.component.ts

import {AppComponent} from '../app.component';
import { Component, OnInit } from '@angular/core';
import { TaskService } from '../task.service';

@Component({
  selector: 'app-new-task-page',
  templateUrl: './new-task-page.component.html',
  styleUrls: ['./new-task-page.component.sass'],
  providers: [TaskService]
})
export class NewTaskPageComponent implements OnInit {
  newTask ?: ToDoTask;
  constructor(private _taskService:TaskService){

  }

  ngOnInit(): void {
  }
  sendTask(task:string,date:string): void{
    this.newTask = new ToDoTask(task,date);
    this._taskService.addTask(this.newTask);
    console.log(this._taskService.getTasks());
  }

}
export class ToDoTask{
  task: string;
  date: string;
  constructor(task:string,date:string){
    this.task = task;
    this.date = date;
  }

}


Solution

  • What I understood from your first statement that you want it to be permanent. Storing is service and retrieving in different component will work until tab reloads.

    This answer right explains the approach. https://stackoverflow.com/a/68272978/2900893

    What you need is storage to store your task and retrieve when/wherever you want.

    localstorage.setItem('task_key', your_task); //  (key, value) value you need to be in string
    

    Same way you can get task by

    localstorage.getItem('task_key')  // This returns your_task which you stored earlier
    

    You can use indexDB as well

    This way your data will be stored permanent even you reload or restart browser.