Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Angular4中的两个组件之间切换时保留或避免丢失数据_Angular - Fatal编程技术网

如何在Angular4中的两个组件之间切换时保留或避免丢失数据

如何在Angular4中的两个组件之间切换时保留或避免丢失数据,angular,Angular,我有一个父组件,包含四个选项卡,每个单独的组件。如果使用[hidden],则在组件之间切换时,我不会释放数据,但当我使用*ngIf时,我会释放填充在组件输入值内的数据。我们如何避免丢失数据?这是因为当您使用[隐藏]时,包含数据的组件没有被破坏,只是没有显示出来。当您使用NGIFT时,组件和数据都会被销毁 为了避免这种情况,您可以使用服务来跟踪您的数据。服务是一个可以存储数据的类,即使所有组件都已销毁,该服务仍将保留数据 服务可以如此简单: import { Injectable } from "

我有一个父组件,包含四个选项卡,每个单独的组件。如果使用[hidden],则在组件之间切换时,我不会释放数据,但当我使用*ngIf时,我会释放填充在组件输入值内的数据。我们如何避免丢失数据?

这是因为当您使用[隐藏]时,包含数据的组件没有被破坏,只是没有显示出来。当您使用NGIFT时,组件和数据都会被销毁

为了避免这种情况,您可以使用服务来跟踪您的数据。服务是一个可以存储数据的类,即使所有组件都已销毁,该服务仍将保留数据

服务可以如此简单:

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

在构造函数中,您可以向组件注入私有服务:ExampleService,然后将其与此.service一起使用。

正如@mika所说,如果您想避免丢失数据,您有两个选择:

不要使用*ngIf指令,而首选[hidden] 使用angular Ngondestory钩子将数据保存到某个位置。此解决方案可能会导致性能问题,具体取决于您如何将其保存到本地存储、数据库等。。。
将数据保存在服务/模型/控制器中,而不是模板中。您可以使用包含所需数据的属性创建一个服务,并将其注入组件。那么为什么不能使用[hidden]呢?