我有一个Angular 7.x应用程序-我具有在服务中调用函数的组件-这会对后端端点执行GET请求并返回用户数组;
我能够看到订阅中的数据(使用console.log的地方)-但是我无法使用subscribe()之外的数据-我如何从this.userAccessList
访问数据
// top of component
public userAccessList: Array<any> = [];
checkAccess(): void {
this.chatMessagesService.getListWithAccessToPage()
.subscribe(json => {
console.log(json); // can see this in the console in the browser
this.userAccessList = json;
});
console.log('userAccessList', this.userAccessList); // appears as an empty array
}
我们在这里处理异步请求。因此,console.log('userAccessList',this.userAccessList);可以在api调用完成之前执行。因此,它那时可能不可用。
如果要在模板中使用此值,请首先检查该值是否存在,如下所示。
<span *ngIf="userAccessList"> <!-- Do stuff --> </span>