【问题标题】:ng2 display object in htmlng2在html中显示对象
【发布时间】:2016-01-17 12:56:19
【问题描述】:

我正在尝试研究如何使用 angular2 在 html 中显示对象。在 ng1 中,我分配了一个变量,并在 html 和 bingo 中用双括号括住了变量名!现在我似乎根本无法显示任何数据。

这是我的简单方法调用:

  onSubmit(value: oSearch): void {
    console.log('you submitted value: ', value);
    Meteor.call('methodName',value.type,value.year,value.idNumber, function(error,result) {
      if (error) {
        console.log('failed', error);
      } else {
        this.oResult = result[0];
        console.log('successful call', this.oResult);
      }
    })
  }

对象被打印到控制台。但我无法通过使用来渲染它:

{{oResult}}

oResult 使用

声明
oResult:Object;

对 ts 和 ng2 完全陌生。

更新

好的,我尝试了 NgZone,但没有成功。我遇到了我真的不明白的行为。

} else {      
console.log('successful call', result[0].topItem);
this.oResult = result[0];
console.log('successful call', this.oResult);

两个 console.logs 都正确打印对象,但 oResult 显示为 [object Object]

如果我改为:

this.oResult.topItem = result[0].topItem

然后我收到 Meteor 错误,第二个 console.log 没有打印。错误是:

Exception in delivering result of invoking 'methodName': TypeError: Cannot set property 'topItem' of undefined

我的服务器方法与 ng1 完美配合。我尝试了同步版本的 http,但行为没有改变。

也许有人知道我可以 fork 使用更新的 angular2-meteor 调用 http 方法的教程演示?

【问题讨论】:

标签: meteor angular


【解决方案1】:

如果字段由在 Angular 区域之外运行的代码更新,Angular 将无法识别值更改。注入zone: NgZone 并运行zone.run(...) 中的代码。在 Angular 中初始化库以使其使用由 Angular 修补的异步 API 也可能就足够了,该 API 会通知 Angular 可能发生的更改。

  constructor(private zone: NgZone) {
  }

  onSubmit(value: oSearch): void {
    console.log('you submitted value: ', value);
    Meteor.call('methodName',value.type,value.year,value.idNumber, function(error,result) {
      if (error) {
        console.log('failed', error);
      } else {
        zone.run(function() {
          this.oResult = result[0];
          console.log('successful call', this.oResult);
        });
      }
    });
  }

有关示例,另请参阅 Service events do not affect template correctly。

【讨论】:

    猜你喜欢
    • 2019-04-17
    • 1970-01-01
    • 2017-02-03
    • 1970-01-01
    • 2020-06-04
    • 2020-09-11
    • 2019-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多