Angular5 - 如何在不丢失数据的情况下返回上一页?

3

我正在使用Angular5,但是在浏览器中返回前一页时会丢失数据。我的意思是,上一个组件应该能够重新加载其数据。

例如:

在我的组件中:

import { Location } from '@angular/common';
@Component({
  selector: 'app-mant-cert-certificacion',
  templateUrl: './mant-cert-certificacion.component.html',
  styles: []
})

export class MantCertCertificacionComponent implements OnInit {

constructor(private location: Location) {
  }
goBack() {
    this.location.back();
    console.log( 'goBack()...' );
  }
}

mant-cert-certificacion.component.html:

<a href="javascript:void(0)" (click)="goBack()">
            <- Back
</a>

这个组件是从我的路由模块调用的。当我点击“返回”按钮时,我希望显示上一个已加载数据的组件。

我的路由模块:

export const routes: Routes = [
  { path: 'xxxx', children: [
    { path: '', component: XComponent},
  ]},
  { path: 'yyyy', children: [
    { path: 'contractdetail/', component: MantCertCertificacionComponent}
  ]}
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class MantenedoresCertRoutingModule { }

有什么想法吗?

之前的组件将是“XComponent”。信息的内容(属性或变量)并不重要,我只想加载它们的数据。

谢谢!


在“XComponent”中,你是如何第一次加载数据的? - Hyuck Kang
2个回答

2
如果您希望在导航期间保留数据,则可以选择以下方法:
  1. LocalStorage
  2. sessionStorage
  3. Services
localStoragesessionStorage 实现了完全相同的功能,并具有相同的API,但是使用 sessionStorage 时,数据仅在窗口或标签页关闭之前保留,而使用 localStorage 时,数据会一直保留,直到用户手动清除浏览器缓存或您的Web应用程序清除数据。
我建议您使用 @ngx-pwa/local-storage 异步本地存储 Angular 库。
对于 Angular 5:
npm install @ngx-pwa/local-storage@5

在你的RootModule中注册它

import { LocalStorageModule } from '@ngx-pwa/local-storage';

@NgModule({
  imports: [
    BrowserModule,
    LocalStorageModule,
    ...
  ]

注入和使用它
import { LocalStorage } from '@ngx-pwa/local-storage';

@Injectable()
export class YourService {

  constructor(protected localStorage: LocalStorage) {}

}

使用方法

let user: User = { firstName: 'Henri', lastName: 'Bergson' };

this.localStorage.setItem('user', user).subscribe(() => {});

服务
创建一个服务并将其注册到Angular模块中。

为什么?如果你想要一个依赖项的实例在整个应用程序中共享,并且可以跨应用程序共享状态,那么你应该在NgModule上进行配置。

使用BehaviorSubject共享数据


-5

Angular 在其历史记录中保留路由详细信息。

window.history.back();

这应该可以工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接