一个可编辑的表单分为两个tab标签页,想要实现第一个tab页上的某个选项选定后,将这个选项选定的内容传到另一个tab页上,可以使用框架提供的服务StorageProvider:
在第一个tab页上引入StorageProvider,StorageProvider代码如下:
/*
* @Date: 2017-09-27 17:57:38
* @Last Modified time: 2018-09-05 17:57:38
* @Description:
* 本地数据存储
* 1、setLocalData : 存储数据,key:value 返回Promise
* 2、getlocalData : 根据键值获取 返回Promise,数据类型Json
* 3、getGenericityData : 根据键值获取 返回Promise, 数据类型T
* 4、removeData : 根据键值删除数据
* 5、clear : 清除session
*/
import { Injectable } from '@angular/core';
import {throwError } from 'rxjs';
import * as JSON from 'circular-json';
@Injectable()
export class StorageProvider {
public localStorage: any;
constructor() {
if (!localStorage) {
throw new Error('Current browser does not support Local Storage');
}
this.localStorage = localStorage;
}
setItem(key: string, value: string): void {
try {
this.localStorage[key] = value;
} catch (error) {
if (error.name === 'QuotaExceededError') {
throwError('超出本地存储限额!');
// 如果历史信息不重要了,可清空后再设置
this.handleQuotaExceededError();
localStorage.setItem(key, value);
}
}
}
getItem(key: string): string {
return this.localStorage[key] || false;
}
setObject(key: string, value: any): void {
try {
this.localStorage[key] = JSON.stringify(value);
} catch (error) {
if (error.name === 'QuotaExceededError') {
throwError('超出本地存储限额!');
// 如果历史信息不重要了,可清空后再设置
this.handleQuotaExceededError();
localStorage.setItem(key, value);
} else {
}
}
}
getObject(key: string): any {
return JSON.parse(this.localStorage[key] || 'null');
}
remove(key: string): any {
this.localStorage.removeItem(key);
}
removeAll(): any {
localStorage.clear();
}
handleQuotaExceededError() {
const tokenInfo = this.getObject('token');
this.removeAll();
this.setObject('token', tokenInfo);
}
}
第一个tab页上,为待传输的选项(表单选项)绑定动作(ngModelChange)="onCompanyChange($event)"
<div nz-col [nzSpan]="24">
<nz-form-item nzFlex>
<nz-form-label nz-col nzRequired [nzSpan]="6" nzFor="companyId">公司</nz-form-label>
<nz-form-control nz-col [nzSpan]="12">
<nz-select style="width: 100%" formControlName="companyId" nzAllowClear="true"
(ngModelChange)="onCompanyChange($event)">
<nz-option *ngFor="let option of companyList" [nzValue]="option.id" [nzLabel]="option.name">
</nz-option>
</nz-select>
<nz-form-explain
*ngIf="getFormControl('companyId')?.dirty&&getFormControl('companyId')?.hasError('required')">
这是必填字段</nz-form-explain>
</nz-form-control>
</nz-form-item>
</div>
在组件上,在绑定的动作上,将选项内容传输给localStorage:
onCompanyChange(event: string) {
this.validateForm1.value.companyId = event;
......
this.storage.setItem('companyId', event);
}
在待接收这个选项内容的tab页上,同样引入StorageProvider,定义一个参数orgId: any;用于接收这个选项:
this.orgId = this.storage.getObject('companyId');