[英]Global object in angular2
如何在angular2中創建全局對象。 我正在使用ionic2中的navParams逐頁(可能是4-5頁)從一頁到另一頁的數據收集。 但想將其存儲在全局對象中並最終提交。 我已經使用全球提供商嘗試了它,但是還沒有得到大多數,也沒有任何線索。 請提出任何建議。
正如我的問題一樣,離子社區建議使用全球供應商。 我確實使用了全局提供程序來保存我的7步表單數據,並在最后一步最后提交。
我與ionic 3一起使用。提供者代碼:
import { Injectable } from '@angular/core';
@Injectable()
export class NcConnectionProvider {
public statecode:any;
public districtcode:any;
constructor() {
//console.log('Hello NcConnectionProvider Provider');
}
}
頁面
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { NcConnectionProvider } from '../../providers/nc-connection/nc-connection';
@IonicPage()
@Component({
selector: 'page-nc-connection',
templateUrl: 'nc-connection.html',
})
export class NcConnectionPage {
public distbform:FormGroup;
public statedata:any;
public districtdata:any;
constructor(public navCtrl: NavController,
public navParams: NavParams,
public ncdatashare: NcConnectionProvider) {
}
locateDistb(form: NgForm){
this.ncdatashare.statecode = this.distbform.value.state;
this.ncdatashare.districtcode = this.distbform.value.district;
}
}
您可以根據需要將provider注入多個頁面並訪問全局變量/對象。 例如在示例this.ncdatashare.statecode = this.distbform.value.state;
值設置為this.ncdatashare.statecode = this.distbform.value.state;
現在,您可以訪問this.ncdatashare.statecode
到其他頁面,但提供程序必須在此處注入。
確保提供一些示例代碼以更好地闡述問題。 此外,以下是您可以遵循的在單個對象中收集數據的方式。
創建一個帶有變量及其getter設置程序的服務。 將此服務注入您的組件中,並在需要的地方設置數據,然后使用其get方法再次將其收集回來。
@Injectable()
export class DataService{
private _data: any;
get data() {
return this._data;
}
set data(data: any) {
this._data = data;
}
}
在你的組件旁邊
@Component({
// configurations
})
export class LoginComponent {
constructor(public dataService: DataService) {
this.dataService.data = { userAge: 37 }
}
}
在需要提交此數據的地方,只需使用吸氣劑將其收集回來即可。
let finalData = this.dataService.data;
不確定您的用例。 但我希望它能對您有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.