在我的 Angular 应用程序中,我正在调用 API 以获取一些“下一阶段”信息。获得该名称后,我将解析该名称,以便可以将其打印到视图中。我在此函数中使用 async/await 。
我看到的是 [Object Object],而不是将“stage”的字符串值打印到视图。
在这种情况下,为什么我的插值显示为
[Object Object]
而不是“常规”?
尝试使用 JSON 管道进行管道连接以查看真实值。
<span class="md-menu-text">{{ (getNextStageName() || 'Not Available') | json }}</span>
这样你就可以看到你的价值观出了什么问题。
所以看起来您正在为 API 调用使用 Promise,而不是 Angular 的 HttpClientModule,后者使用 rxjs 并返回解析的 JSON 作为默认值。话虽这么说,你可能需要解析你的承诺中的 json...
public async getNextStage(staffId) {
const response = await API.service.send({
reqType: 'get',
req: `staff/history/next`,
reqArgs: {id: staffId}
});
return response.json
}
不要绑定到函数,而是绑定到变量。
您需要做的就是在组件中声明一个变量,如下所示:
nextStageName = 'Not Available';
在视图中绑定到它 -
{{nextStageName}}
服务返回值后,将其分配给此变量。
视图将显示“不可用”,直到服务获得新值。视图将自动更新。
所以这就是发生的事情:
您认为是
string
的属性实际上是一个对象。当你在模板中使用字符串插值语法({{}}
)时,Angular 会调用它的 toString
方法。在 toString
上调用 Object
会产生 [Object Object]
。
因此,一旦您从 API 获得响应,您就需要确定要在视图上打印什么内容。阶段名称可能是您实际从服务接收到的响应数据的字段值。
下面是一个模拟示例(利用 JSONPlaceholder API),说明您将如何执行此操作:
import { Component } from '@angular/core';
import { StageService } from './stage.service';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
stageData: any; // This would be assigned an Object that your service method results
constructor(private stageService: StageService) {}
async ngOnInit () {
this.stageData = await this.stageService.getStageData();
// Log it to the console to see it's structure and look for the property you want to use on the UI.
// For this specific example, the response data will have a name property that I'm using on the HTML(Template)
console.log('Got the Stage Data as: ', this.stageData);
}
}
在模板中:
<!--
Here since the data is going to be assigned asynchronously
but the template would already be in the process of initialization,
I'm using the *ngIf directive to check.
If the stageData is still undefined, I'm displaying the elseBlock
-->
<div *ngIf="stageData; else elseBlock">
<h1>Stage Name</h1>
<p>Wrong Syntax: {{ stageData }} - Will print [Object object] as stageData is an Object and NOT A STRING</p>
<p>Right Syntax: {{ stageData.name }}</p>
</div>
<ng-template #elseBlock>
<h1>Loading...</h1>
</ng-template>
这里有一个 StackBlitz 示例供您参考。
PS:请密切关注评论。
对于字符串插值请记住:
var x = `my name is ${name}` // CORRECT
var x = `my name is ${{name}}` // INCORRECT