angular - 路由更改时角度数据不会持续存在
问题描述
实际上我是 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 数组变空了如何解决这个问题?
解决方案
发生这种情况是因为当您导航到另一个组件时,您的实际组件会被破坏,从而丢失您的 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)
}
推荐阅读
- angular - angular ngxs dispatch call subscribe 多次
- ios - 如何为 iOS 应用实现大纲视图(如 NSOutlineView)?
- c# - 在 ASP.NET API 中发布数组
- javascript - 是否有任何推荐的 JS 库/框架来从 html 中提取文本?
- python - 使用 lxml 的 Python 脚本,xpath 返回空列表
- html - 同时为不同的 div 标签使用两个包含相同样式属性的 css 文件
- sql - 如何创建存储过程以在 Sql server 中创建表,其中表的名称将按年份更改,例如 Order2019
- c++ - Eigen::MatrixXf 到 std::vector
- javascript - 我的引导导航栏没有显示在移动设备上
- python-3.x - 数据库验证在 for 循环中不起作用