Javascript Angular 2服务变量在模板中引用时给出控制台错误

Javascript Angular 2服务变量在模板中引用时给出控制台错误,javascript,angular,Javascript,Angular,我试图显示从服务检索到的数据,并将其显示在HTML中。我的方法可以工作,但它在控制台中输出错误,我不知道如何解决它们 以下是我的应用程序的工作原理: 应用程序组件.ts // initialize the variable that will store the returned message object messages: any; // call the service this.TaskService.getMessages() .subscribe(response =>

我试图显示从服务检索到的数据,并将其显示在HTML中。我的方法可以工作,但它在控制台中输出错误,我不知道如何解决它们

以下是我的应用程序的工作原理:

应用程序组件.ts

// initialize the variable that will store the returned message object
messages: any;

// call the service
this.TaskService.getMessages()
  .subscribe(response => {
     // response will be an object with two key:value pairs inside
     this.messages = response;
  });
以及如何在我的html中显示它:

<div>
   <span class="hello">{{messages.hello}}</span>
   <span class="goodbye">{{messages.goodbye}}</span>
</div>

{{messages.hello}
{{留言,再见}
每当我运行此操作时,html值都会正确显示,但我在控制台中收到以下错误:

错误类型错误:无法读取未定义的属性“hello”

错误类型错误:无法读取未定义的属性“再见”

我的理论是,为什么会发生这种情况,是因为在模板尝试加载值时,服务还没有完成对这些值的检索。但是,如果是这样的话,我不知道如何解决它

(除了创建初始化“hello”和“再见”的组件级变量,然后在服务完成其调用时更改它们的值,但这似乎效率低下)

如何显示从服务中检索的值,并在HTML中显示它们,而不出现控制台错误

感谢您的帮助。

您可以使用
?。
来防止
消息
为空的情况:

<div>
   <span class="hello">{{messages?.hello}}</span>
   <span class="goodbye">{{messages?.goodbye}}</span>
</div>

{{留言?.hello}
{{留言?.再见}
您可以使用
?。
来防止出现
消息
为空的情况:

<div>
   <span class="hello">{{messages?.hello}}</span>
   <span class="goodbye">{{messages?.goodbye}}</span>
</div>

{{留言?.hello}
{{留言?.再见}

出现该错误是因为在呈现模板时,
消息的值仍然未定义,因为它是异步分配的。有几种方法可以解决此问题:

1.埃尔维斯操作员 Angular支持在绑定html模板时使用

<div>
   <span class="hello">{{messages?.hello}}</span>
   <span class="goodbye">{{messages?.goodbye}}</span>
</div>
或者,如果您相信对象的真实性:

<div *ngIf="messages">
   <span class="hello">{{messages.hello}}</span>
   <span class="goodbye">{{messages.goodbye}}</span>
</div>

{{messages.hello}
{{留言,再见}

出现该错误是因为在呈现模板时,
消息的值仍然未定义,因为它是异步分配的。有几种方法可以解决此问题:

1.埃尔维斯操作员 Angular支持在绑定html模板时使用

<div>
   <span class="hello">{{messages?.hello}}</span>
   <span class="goodbye">{{messages?.goodbye}}</span>
</div>
或者,如果您相信对象的真实性:

<div *ngIf="messages">
   <span class="hello">{{messages.hello}}</span>
   <span class="goodbye">{{messages.goodbye}}</span>
</div>

{{messages.hello}
{{留言,再见}