我是离子2中的新手,我在页面之间的数据时遇到麻烦。在我的home.ts文件中,我有一个全局数组,其中包含我计算的一些数字,我想将其传递到我的表文件。
这是home.ts中的函数。
`import { Component } from '@angular/core';
import { AlertController } from 'ionic-angular';
import { IonicPage,NavController, NavParams} from 'ionic-angular';
import {Table} from '../table/table';
export class HomePage {
averagesList: Array <number> =[];
constructor(public alerCtrl: AlertController,
public navCtrl: NavController,
public navParams: NavParams)
{}
Calculate(){
var Averages=[];
//Calculations on the 'Averages' Array
this.averagesList = Averages;
this.navCtrl.push(Table,this.averagesList);
}
}
所以我尝试将其打印在我的table.ts文件中,但它给了我未定义的结果
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import {HomePage} from '../home/home';
@IonicPage()
@Component({
selector: 'page-table',
templateUrl: 'table.html',
})
export class Table{
constructor(public navCtrl: NavController, public navParams: NavParams) {
}
ionViewDidLoad() {
console.log(this.navParams.get('averagesList'));
}
}
我试图通过一个让变量并起作用,所以它为什么不适合数组?
您的错误是使用console.log(this.navParams.get('averagesList'));
在这里'Awerageslist'是关键。
要以这种方式获得它,您需要发送为:
this.navCtrl.push(Table,{'averagesList' : this.averagesList});
else:
如果您直接发送为
this.navCtrl.push(Table,this.averagesList);
您可以像这样检索值:
console.log(this.navParams.data);
您可以使用服务来实现。就像在Angular2中您可以在构造函数中导入服务并使用这样的属性。
import {OnInit} from '@angular/core';
import {someService} from ./somepath;
...
export class someClass implements OnInit{
let myTmpVar; //we will capture the shared data in this variable
constructor (private smService: someService){ ... }
ngOnInit{
this.myTmpVar = this.smService.SharedServiceData;
}
...
}
最好使用服务传递嵌套数据。在您的情况下计算对象。
您可以创建消息服务并收听更改,如下所示。
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs';
import {Subject} from 'rxjs/Subject';
@Injectable()
export class LocalMsgService {
private subject = new Subject();
sendMessage(message) {
this.subject.next(message);
}
clearMessage() {
this.subject.next();
}
getMessage(): Observable<any> {
return this.subject.asObservable();
}
}
可以在您的home.ts和table.ts页面中使用的内容如下
home.ts
//other imports comes here
import {LocalMsgService} from 'services/localMsg';
@Component({
selector: 'home-component',
templateUrl: 'home.html'
})
export class HomePage {
constructor( private msgService: LocalMsgService) {
}
dataToPass() {
console.log(this.averagesList);
this.msgService.sendMessage(this.averagesList);
}
}
table.ts
//other imports comes here
import {LocalMsgService} from 'services/localMsg';
import {Subscription} from 'rxjs/Subscription';
@Component({
selector: 'page-table',
templateUrl: 'table.html',
})
export class TablePage{
items: any;
subscription: Subscription;
constructor(
public localMsgService : LocalMsgService) {
this.subscription = this.localMsgService.getMessage().subscribe(msg => {
this.items = msg;
});
}
}