【问题标题】:cannot able to get values using any = {} in typescript angular8无法在 typescript angular8 中使用 any = {} 获取值
【发布时间】:2020-04-19 11:45:05
【问题描述】:
import { Component, OnInit  } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { enableProdMode } from '@angular/core';
enableProdMode();

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
   values: any = {};


  constructor(private http: HttpClient) { }

  ngOnInit() {
    this.getValues();
    console.log(this.values);
  }

   getValues()
   {
     this.http.get('http://localhost:5000/api/values').subscribe(Response => { this.values = Response},error => {console.log(error); 
     });
   }

}

我可以从 HTTP 响应中获取值。但我无法将这些值存储在“值”对象中。得到空数组。

【问题讨论】:

    标签: angular typescript tslint


    【解决方案1】:

    您需要将 console.log 放在订阅中,因为它在执行 console.log 时被异步调用,所以没有结果。

    getValues()
    {
         this.http.get('http://localhost:5000/api/values').subscribe(Response => { 
            this.values = Response;
            console.log("##Got values", this.values);
            },error => {console.log(error);      
       });
    }
    

    【讨论】:

    • 是的,我明白了。但我无法在另一个组件中使用这些值。导出类 RegisterComponent 实现 OnInit { @Input() valuesFromHome: any;型号:任何 = {};构造函数() { }
    • 这完全是一个不同的问题
    猜你喜欢
    • 2019-02-17
    • 2012-07-14
    • 2019-07-23
    • 1970-01-01
    • 2018-07-26
    • 2020-03-01
    • 2020-06-16
    • 2018-02-12
    • 2018-10-01
    相关资源
    最近更新 更多