离子2 - 动态更改状态栏的颜色

时间:2017-06-08 22:11:49

标签: javascript cordova ionic-framework ionic2

我正在尝试在离子状态栏中更改状态栏颜色,具体取决于获取的参数。

只有colorStatusBar函数中的onDeviceReady()变量显示为undefined

有人可以帮我解决这个问题吗?

typeColor: string;
colorStatusBar: string;

constructor(public navCtrl: NavController, public navParams: NavParams, statusBar: StatusBar){
    this.typeColor = this.navParams.get('type');
    if(this.typeColor == "value1"){
      this.colorStatusBar = "#F44336";
    }
    if(this.typeColor == "value2"){
      this.colorStatusBar = "#66BB6A";
    }
    if(this.typeColor == "value3"){
      this.colorStatusBar = "#9E9E9E";
    }

    document.addEventListener("deviceready", onDeviceReady, false);
    function onDeviceReady() {
          console.log(this.colorStatusBar) // undefined
          statusBar.backgroundColorByHexString(this.colorStatusBar);
    }
}

2 个答案:

答案 0 :(得分:0)

你可以通过在ionViewDidLoad()内移动逻辑(在构造函数之后运行)并使用platform.ready()来确保Cordova启动来实现:

ionViewDidLoad() {
    this.typeColor = this.navParams.get('type');

    this.platform.ready().then(() => {
        if(this.typeColor == "value1"){
            this.statusBar.backgroundColorByHexString("#F44336");
        }
        if(this.typeColor == "value2"){
            this.statusBar.backgroundColorByHexString("#66BB6A");
        }
        if(this.typeColor == "value3"){
            this.statusBar.backgroundColorByHexString(#9E9E9E");
        }
    }
}

在这种情况下,您的构造函数会更改为:

constructor(public navCtrl: NavController, public navParams: NavParams, public statusBar: StatusBar, public platform: Platfom){
    // empty :), but notice the dependency injection of Platform
}

请勿忘记在顶部导入Platform

import { Platform } from 'ionic-angular';

要使您的特定示例正常工作,您需要确保从父网页调用此当前页面,并且还传入参数type

所以在父页面中(你还没有共享代码)你需要这样的东西:

export class ParentPage {
  constructor(public navCtrl: NavController) {
  }

  pushPage(){
    // push another page onto the navigation stack
    // causing the nav controller to transition to the new page
    // optional data can also be passed to the pushed page.
    this.navCtrl.push(MyStackOverflowSharedPage, {
      type: "value2"
    });
  }
}

有关详细信息,请阅读NavController上的文档。

答案 1 :(得分:0)

我只能按照以下方式工作:

import { Component } from '@angular/core';
import { NavController, NavParams, Platform } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';

...

typeColor: string;
constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    public statusBar: StatusBar,
    public platform: Platform){

        this.typeColor = this.navParams.get('type');
        this.platform.ready().then(() => {
            if(this.typeColor == "value1"){
                statusBar.backgroundColorByHexString("#F44336");
            }
            if(this.typeColor == "value2"){
                statusBar.backgroundColorByHexString("#66BB6A");
            }
            if(this.typeColor == "value3"){
                statusBar.backgroundColorByHexString("#9E9E9E");
            }
        })
}

...