Amar Singh
Amar Singh

Reputation: 5622

Issue with the service function -Angular

task.service.ts

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

@Injectable()
export class TaskService {
   private tasklist= [{taskname:"sample task",taskdetail:"This is a test task",status:"todo"}];

  constructor() { }

  getTasklist(chosenstatus){
    return this.tasklist.filter((e)=>{

        if(e.status==chosenstatus){

          return e;

        }
    });

  }

  addTask(name,task){
    console.log(this.tasklist);/*this shows new task added*/
    this.tasklist.push({taskname:name,taskdetail:task,status:"todo"});
  }

}

Above is my service. After I add a task using addTask function, it adds the new task object into the task array but does not show while listing.

create-new.component.ts - to add new

     import { Component, OnInit } from '@angular/core';
import { TaskService } from '../task.service';
@Component({
  selector: 'app-create-new',
  templateUrl: './create-new.component.html',
  styleUrls: ['./create-new.component.css']
})
export class CreateNewComponent implements OnInit {
  taskservice;
  constructor(taskservice :TaskService) {
    this.taskservice= taskservice;
   }

  ngOnInit() {
  }

  onSubmit(form){

    this.taskservice.addTask(form.value.cardheading,form.value.cardcontent);
  }

}

task.component.ts - to show list

@Component({
  selector: 'app-task',
  templateUrl: './task.component.html',
  styleUrls: ['./task.component.css']
})
export class TaskComponent implements OnInit {
@Input() sts;
  todoService;
  taskService;
  constructor(toDoS:TaskService) { 
    this.taskService=toDoS;
  }

  ngOnInit() {
    this.todoService=this.taskService.getTasklist(this.sts);
  }

}

Upvotes: 1

Views: 48

Answers (1)

P.S.
P.S.

Reputation: 16384

Your variable todoService in component doesn't update real-time because you just call this operation ones on component init and finally you have simple variable without binding to tasklist variable from service.

Your case is a perfect time for Rxjs and BehaviorSubject. This way you can subscribe to changes and get new value after it was updated. Here is simple abstract example of what you want:

STACKBLITZ

Here I modify service variable from one component, and it affects the variable in another component real-time. All magic goes here:

enter image description here

All you need is just to call setVariableHolder method to set new value:

this._abstractService.setVariableHolder('valueGoesHere'); // Replace 'valueGoesHere' string with any data you need

and getVariableHolder to get the updated value:

this._abstractService.getVariableHolder().subscribe(val => {
  this.anyComponentVariable = val;
})

Upvotes: 1

Related Questions