angular - 当我在Angular4中的两个组件之间切换时如何保留或避免丢失数据
问题描述
我有一个父组件,包含四个选项卡,每个选项卡都是单独的组件。如果使用 [hidden],那么在组件之间切换时我不会丢失数据,但是当我使用 *ngIf 时,我会丢失我在组件的输入值中填充的数据。我们如何避免丢失数据?
解决方案
那是因为当您使用[hidden]
包含数据的组件时,它并没有被破坏,只是没有显示出来。当您使用ngIf
该组件时,该组件将被销毁,您的数据也是如此。
为避免这种情况,您可以使用服务来跟踪您的数据。服务是一个可以存储你的数据的类,即使所有组件都被销毁,服务仍然会有数据。
服务可以像这样简单:
import { Injectable } from "@angular/core";
@Injectable()
export class ExampleService {
someDataYouWantToKeep:string = "data"
someOtherDataYouWantToKeep:number = 1
}
然后在您的组件中,您可以像这样使用它:
import { Component, OnInit } from '@angular/core';
import { ExampleService } from '<path to file>';
@Component({
selector: 'app-setup',
templateUrl: './setup.component.html',
styleUrls: ['./setup.component.scss']
})
export class ExampleComponent implements OnInit {
constructor(private service: ExampleService) { }
ngOnInit() {
console.log(this.service.someDataYouWantToKeep)
this.service.someOtherDataYouWantToKeep = 2
}
}
在构造函数中,您可以注入组件,private service: ExampleService
然后将其与this.service
.
推荐阅读
- php - compact():未定义变量:运算符
- php - 从子函数返回重定向
- java - 通过歌曲名称和艺术家姓名查找歌曲的算法,匹配最接近的字符串
- css - 用光标关闭时更改主 Wordpress 菜单悬停颜色
- javascript - 如果锚点中包含关键字,如何突出显示文本?
- ruby-on-rails - Rails 不会把我带到重置密码表单,不断地重定向我
- python - 美丽的汤在一个网站上返回空列表,但在另一个网站上有效
- javascript - 如何在 xmlHTTPRequest 之前将 cookie 值插入到 Authorization 标头中?
- android - Google 地图的资源缺失或不正确
- flutter - 嵌套可重新排序的列表?