Angular2。组件中的方法被多次调用并返回错误的数据

时间:2017-12-05 11:29:57

标签: angular-cli angular2-services

我在模块内部有一个方法,当页面加载时它会被调用3次,并返回错误的数据。当调试/检查控制台时,它显示为正在返回正确的数据,但在屏幕上显示数据错误

在component.html中我有

model.addAttribute("form", basicForm);
model.addAttribute("addOrEdit",ADD_OR_EDIT.ADD);
in edit:

model.addAttribute("form", editForm);
model.addAttribute("addOrEdit",ADD_OR_EDIT.EDIT);


<form action="#" th:action="(${addOrEdit.thAction})" class="form-horizontal form-narrow" th:object="${form}"
      method="post">

这是方法:

<p ng-if="posting">
 {{ getPlaceholderText('headline') }}
</p>

当呈现页面时,输出:

getPlaceholderText(placeholderName: string): string {

console.log('Looking for placeholder with name "' + placeholderName + '"');

if (this.posting.placeholders != null) {

  this.posting.placeholders.forEach(placeholder => {
    if (placeholder.name === placeholderName) {
      console.log('found placeholder with name "' + placeholderName + '"');
      console.log('Returning value: "' + placeholder.text + '"');
      console.log('');
      return placeholder.text;
    }
  });
} else {
  return 'posting.placeholder is null';
}

console.log('');
console.log('placeholder with name "' + placeholderName + '" not found');
return 'placeholder with name "' + placeholderName + '" not found';
}

它应该是placeholder.text属性的值。在控制台中我有这个:

placeholder with name "headline" not found

任何人都可以对这里发生的事情有所了解吗?

以下是我的组件的完整代码:

Looking for placeholder with name "headline"
found placeholder with name "headline"
Returning value: "Standard Post 1 headline"

placeholder with name "headline" not found

Looking for placeholder with name "headline"
found placeholder with name "headline"
Returning value: "Standard Post 1 headline"

placeholder with name "headline" not found

2 个答案:

答案 0 :(得分:0)

尝试以下方法: <p *ngIf="posting"> {{ getPlaceholderText('headline') }} </p>

答案 1 :(得分:0)

ahhh“forEach”不是TypeScript。它是javascript,所以

this.posting.placeholders.forEach(placeholder => {

应该是

for (const placeholder of this.posting.placeholders) {

然后它起作用