首页 > 解决方案 > 路由更改时角度数据不会持续存在

问题描述

实际上我是 Angular 应用程序的新手,我正在尝试创建一个简单的 AddTodo 应用程序这是我的 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
     }

这是我的 Todos 组件

  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)
  }

并从getTodos()方法中获取 todos 并将其保存到 Todos 数组中

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>

在我的 Todos component.html 中,我添加了一个按钮,它基本上将我路由到localhost:90/add ,当我尝试返回时,todos 数组变空了如何解决这个问题?

标签: angulartypescript

解决方案


发生这种情况是因为当您导航到另一个组件时,您的实际组件会被破坏,从而丢失您的 todos 数组。

您要做的就是将您的 TodosService 放在 todos 组件父级(例如应用程序组件)的提供者中:这样您的 todos 就不会被破坏

app.component.ts

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

Todos 服务中

注意:请使用 @Injectable() 而不是 @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; }
  );
}

Todos 组件中

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)
}

推荐阅读