首页 > 解决方案 > 无法将服务中的数据放入窗口变量(此)

问题描述

我试图把data[0]from ApiServiceto 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
  }
}

标签: angulartypescript

解决方案


发生这种情况是因为您正在进行异步调用,因此第一次打印 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
}

推荐阅读