【问题标题】:Cannot assign Cordova plugin returned value to views in Ionic2无法将 Cordova 插件返回值分配给 Ionic2 中的视图
【发布时间】:2017-11-13 02:47:44
【问题描述】:

在我的 ionic2 应用程序中,我尝试使用 Ionic Native 中未包含的 Cordova 插件。我在这里参考了 Josh Morony 写的文章:https://www.joshmorony.com/using-cordova-plugins-in-ionic-2-with-ionic-native/。一切正常(代码已编译,执行没有问题)。

由于Ionic Native不支持这个插件,所以没有promise和observable,需要一些时间来响应。这个插件确实返回了值。我试图将插件的返回值分配给我的视图,但它失败了(错误消息:TypeError:null 不是对象(评估 'this.name=t'))。

PS:如果我只是将响应放入警报,警报(响应),它会正确显示返回值。

下面是我的代码,有人可以帮帮我吗?非常感谢:-)

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Platform } from 'ionic-angular';

declare var airwatch;
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  name: string = null;
  constructor(public navCtrl: NavController, platform: Platform) {

    // code starts here
    platform.ready().then(() => {
      (<any>window).plugins.airwatch.username(function(response){

        alert(response);// this alert works! it will correctly show the response in text mode (the response is text)

        this.name = response; // the line failed, it said: cannot insert null to this.name but I thought the response is text and it works when I use alert or console.log

      }, function(error){
        this.name = error;
      });


    });

  }

}

我也尝试将代码放在 ionViewDidLoad() {} 中,但还是不行。相同的错误信息:TypeError: null is not an object (evalating 'this.name=t')

我尝试了 NgZone,但没有成功。

是不是因为返回的值不在角度“范围”内?

【问题讨论】:

  • 会不会是因为视图还没准备好?

标签: angular ionic2 cordova-plugins airwatch


【解决方案1】:

您需要保留对“this”的引用,因为回调中的第二个“this”是相对于回调的。

所以添加

let self = this;

在调用插件之前,您可以在回调中使用新创建的“self”变量。你的代码看起来像

let self = this;

(<any>window).plugins.airwatch.username(function(response){
   alert(response);// this alert works! it will correctly show the response in text mode (the response is text).  

this.name = response; // the line failed, it said: cannot insert null to self.name but I thought the response is text and it works when I use alert or console.log

              }, function(error){
                self.name = error;
              });

https://stackoverflow.com/a/36357403

【讨论】:

  • 非常感谢约翰 :-)
猜你喜欢
  • 1970-01-01
  • 2016-09-13
  • 2016-12-24
  • 1970-01-01
  • 2017-09-27
  • 2020-02-17
  • 1970-01-01
  • 1970-01-01
  • 2019-12-30
相关资源
最近更新 更多