在非相关组件之间传递价值

时间:2018-06-20 21:46:11

标签: angular typescript ionic-framework ionic3

我希望将值从Tabs组件传递到Task组件,我创建了一个单独的数据服务。制表符中的值是从其他组件获取的参数。尝试获取将选项卡中的值传递给任务组件时,它在任务页面中给了我“未定义”的信息。

我的服务班

import { Injectable} from '@angular/core';  

@Injectable()
export class DataService {

   list:any;

   getUserData(){ 
      return this.list; 
   } 
   setUserData(data:any){
       this.list = data;
   }
}

标签组件

import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { SettingsPage } from '../settings/settings';
import { TasksPage } from '../tasks/tasks';
import { DataService } from "../../services/data.service";

@Component({
  templateUrl: 'tabs.html',
  providers:[DataService]
})
export class TabsPage {

  tab1Root = TasksPage;
  tab2Root = SettingsPage;
  user:any;

  constructor(public navCtrl: NavController, public navParams: NavParams,public dataService: DataService) {

  this.user = navParams.get('param1');    
  this.dataService.setUserData(this.user);
  }
}

任务页面

import { Component,ViewChild } from '@angular/core';
import { DataService } from "../../services/data.service";
import { TabsPage } from '../tabs/tabs';
import { TasksCreatePage } from '../tasks-create/tasks-create';

const logger = new Logger('Tasks');

@Component({
  selector: 'page-tasks',
  templateUrl: 'tasks.html',
  providers:[DataService]
})
export class TasksPage {
usern:any;

constructor(public dataService: DataService){
this.usern = this.dataService.getUserData();
console.log(this.usern);
}

1 个答案:

答案 0 :(得分:0)

我认为问题在于navParams.get()是一个异步函数。 替换为:

this.user = navParams.get('param1').then( () => {
    this.dataService.setUserData(this.user);
});

对此:

this.user = navParams.get('param1');    
this.dataService.setUserData(this.user);