angular - 打字稿非空数组返回长度为零
问题描述
目前无法理解我的以下代码的问题。任何建议或信息都非常受欢迎!
getProjects(client):string[] {
client = client.trim();
var tempProjects = [];
// if(this.m_projects.length >= 1){
// this.m_projects = [];
// this.m_tasks = [];
// this.sTask = null;
// this.sProject = null;
// }
const curTaskObservable = this.afs.collection('users').doc('myFirstUser')
.collection('clients').doc(client).collection('projects')
.valueChanges()
.subscribe((data:any)=>{
data.forEach(el=>{
if(this.m_projects.indexOf(el.name) === -1){
this.m_projects.push(el.name);
tempProjects.push(el.name);
}
});
});
console.log("array length : " + tempProjects.length);
console.log(" array content : " + tempProjects);
return tempProjects;
如下所示,输出打印长度“0”,数组内容打印长度“1”。这怎么可能,有没有办法获得正确的长度值。谢谢!
解决方案
subscribe((data:any)=>{
data.forEach(el=>{
if(this.m_projects.indexOf(el.name) === -1){
this.m_projects.push(el.name);
tempProjects.push(el.name);
}
});
});
console.log("array length : " + tempProjects.length);
console.log(" array content : " + tempProjects);
return tempProjects;
数组不是空的。就是你还没有理解异步代码是如何执行的。订阅中的块可以在console.log
打印数组大小之后执行。
移动console.log
订阅块内部。
subscribe((data:any)=>{
data.forEach(el=>{
if(this.m_projects.indexOf(el.name) === -1){
this.m_projects.push(el.name);
tempProjects.push(el.name);
console.log("array length : " + tempProjects.length);
}
});
});
这将是了解异步代码如何工作的一个很好的步骤。
推荐阅读
- javascript - 合并查询列表视图后的Firestore获取重复数据
- python - 如何加载 keras 模型并从停止的地方重新开始训练
- c - 无法将颜色传递给 FragmentShader
- r - R中聚集堆积条形图中每个组的单独标签
- javascript - 无法读取未定义 electron.js 的属性“请求”
- android - 如何将 Flutter WearOS 应用发布到 Play 商店
- amazon-web-services - 如何在 Auto Scaling 事件中立即运行 AWS Lambda 函数?
- amazon-web-services - 节点应用程序 docker 映像在本地运行并在 Amazon ECS 上失败
- c# - 我们是否需要维护每个订阅将具有唯一的 EventType 或者多个订阅可以在 Azure EventGrid 域中具有相同的 EventType
- templates - Google Web 应用程序 - 访问模板脚本中的变量