Himanshu Rahi
Himanshu Rahi

Reputation: 301

Angular Data not persist when route changes

Actually am new in Angular app am trying to create a simple AddTodo app Here is my TodosService

this.Todos = this.af.collection('Todos').snapshotChanges().pipe(map(changes => {
      return changes.map(a => {
        return { id: a.payload.doc.id, ...a.payload.doc.data() }

      })
    })) 
    getTodos() {
    return this.Todos
     }

and here is my Todos Component

  todos = []
  constructor(private todosService: TodosService, private route: ActivatedRoute, private router: Router) { }
  ngOnInit() {

    console.log('todos component')
    this.todosService.getTodos().subscribe(todo => {
      this.todos = todo
      console.log(this.todos)
    }) 
  }

  onTodo(todo) {
    this.router.navigate(['/edit', todo.id])
    this.todosService.TodoToEdit(todo)
  }

and from getTodos() method am getting todos and save it into Todos array

Todos.component.html

<div *ngIf="todos.length > 0">
    <ul class="collection">
        <li class="collection-item" (click) = 'onTodo(todo)' style="cursor: pointer;" *ngFor="let todo of todos">
            {{todo.title}}

        </li>
    </ul>
</div>

and in my Todos component.html i have add button which basically routes me to localhost:90/add and wheneven i try to go back then todos array get empty how to fix this?

Upvotes: 0

Views: 1881

Answers (1)

Freeky
Freeky

Reputation: 820

This happens because when you navigate to another component, your actual component gets destroyed, losing your todos array.

What you have to do is placing your TodosService in the providers of todos component parent (for example app component): this way your todos will not be destroyed

app.component.ts

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  providers: [TodosService]
})

in TodosService

NOTE: please use @Injectable() instead of @Injectable({provideIn: 'root'})

todos = [];

this.Todos = this.af.collection('Todos').snapshotChanges().pipe(map(changes => {
  return changes.map(a => {
    return { id: a.payload.doc.id, ...a.payload.doc.data() }
  })
}));

getTodos() {
  this.Todos.subscribe(
    todo => { this.todos = todo; }
  );
}

in TodosCompomponent

get todos() { return this.todosService.todos }
constructor(private todosService: TodosService, private route: ActivatedRoute, private router: Router) { }

ngOnInit() {
  console.log('todos component')
  this.todosService.getTodos();
}

onTodo(todo) {
  this.router.navigate(['/edit', todo.id])
  this.todosService.TodoToEdit(todo)
}

Upvotes: 1

Related Questions