angular - 在Angular http方法中分配函数外的响应值
问题描述
用户.component.ts
ngOnInit(): void
{
var data;
this.auth=this.cookie.get("auth");
this.servicefetch.ContactList(this.auth).subscribe
(
(response)=>
{
data=response;
},
(error)=>{console.log(error)}
);
}
服务CRUD.service.ts
ContactList(auth:String)
{
const headers = { "content-type": "application/json", "Authorization": "Contacts " + auth };
return this.http.get<any>('http://localhost:8080/contacts', {headers});
}
在这里,我想将响应分配给另一个变量说数据。但是当我打印出数据时,我得到了不确定。我认为这是因为这是异步的。任何方式我都可以将它分配给变量数据
解决方案
您必须在 Component 类的范围内声明您的状态变量。
export default App extends Component {
data: any;
ngOnInit(): void
{
this.auth=this.cookie.get("auth");
this.servicefetch.ContactList(this.auth).subscribe
(
(response)=>
{
this.data=response;
// call the next callback (store the token or go to next route)
},
(error)=>{console.log(error)}
);
}
}
您可以像这样签入模板:
<div *ngIf="data">
data.yourProperty
</div>
推荐阅读
- algorithm - 伪代码的成本常数
- javascript - 单击时从类元素更改此样式属性
- apache-kafka - 如何在 kafka 上缓存流数据?
- groovy - 有没有一种从外部文件读取 Groovy 映射的简单安全方法?
- amcharts - 按替代数据属性对 amcharts4 树图进行排序
- google-sheets - 从 Google 表格生成发票
- powershell - Azure Active Directory webhook 密码过期,向团队发送通知
- python - 如何使用 plotly dash 获得准确的时间间隔?
- r - R中的范围条形图
- firebase - Firebase CustomClaims 存储在哪里