首页 > 解决方案 > 当我在Angular4中的两个组件之间切换时如何保留或避免丢失数据

问题描述

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

标签: angular

解决方案


那是因为当您使用[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.


推荐阅读