angular - 无法将服务中的数据放入窗口变量(此)
问题描述
我试图把data[0]
from ApiService
to this.data
。
然而,它失败了。有人可以指导我吗?
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ApiService } from '../services/api.service';
@Component({
selector: 'app-card-details',
templateUrl: './card-details.component.html',
styleUrls: ['./card-details.component.scss']
})
export class CardDetailsComponent implements OnInit {
name: string = "";
data: any;
constructor(
private route: ActivatedRoute,
private apiService: ApiService,
) { }
ngOnInit() {
this.getData();
}
getData(){
this.route.params.subscribe(params => this.name = params['name']);
this.apiService.getName(this.name).subscribe(data => {
this.data = data[0];
console.log(this.data); \\ console.log at here able to show the value of this.data
})
console.log(this.data); \\ console.log at here NOT able to show the value of this.data
}
}
解决方案
发生这种情况是因为您正在进行异步调用,因此第一次打印 this.data 时,信息尚未到达。但是,当异步调用收到信息时,您的 console.log 里面会打印信息。作为练习,只要在 asyn 调用中有响应放入,然后在 console.log 中打印 this.data,您就会看到信息存在。
getData(){
this.route.params.subscribe(params => this.name = params['name']);
this.apiService.getName(this.name).subscribe(data => {
this.data = data[0];
console.log(this.data); \\ it prints when receive the data (async)
})
console.log(this.data); \\ it prints although the data is not prensent
}
推荐阅读
- cmd - Eclipse Foundation 命令行导入引发错误
- sas - 在 SAS 中跟踪失败的作业
- bash - 每半小时安排一次从晚上 10 点到凌晨 1 点的 cron
- javascript - Javascript:如何捕获在 video.play() 中加载视频的错误?
- python - 在 Python 中使用斯坦福解析器提取通用依赖项
- r - adonis2“by=margin”选项的自由度不准确
- amazon-web-services - 用于过滤的弹性搜索与 Dynamodb
- cakephp - CakePHP 3.8 / CakePHP 4 vs CakePHP 2 中原始 SQL 查询结果的数组结构
- node.js - 你应该如何在 Webpack 配置中为字体格式化输出路径?
- javascript - 使用上下文进行反应状态过滤