将API中的数据存储在变量[Angular]中 [英] Store data from API in variable [Angular]

查看:64
本文介绍了将API中的数据存储在变量[Angular]中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从API获取数据的服务: https://jsonplaceholder.typicode.com/posts/1

I have a service which gets data from API : https://jsonplaceholder.typicode.com/posts/1

但是我不能在变量中存储数据

but i can not store data in variable

代码:Service.ts

Code : Service.ts

public urlServer : string = "https://jsonplaceholder.typicode.com/posts/1";

public getAllProjectsFromAPI() : Observable<any> {
   return this.http.get( this.urlServer, { responseType: 'json' } ); 
}

Component.ts

Component.ts

constructor( private projects : ProjetsService ) { }

  ngOnInit() {
    this.projects.getAllProjectsFromAPI().subscribe( data => this.test = JSON.stringify( data ) );
    console.log( this.test );
  }

我尝试对var测试控制台,但未定义

I try to console test var and i get undefined

推荐答案

您正在尝试记录尚未计算的值.

Your are trying to log a value which is not yet computed.

// this block is asynchronous
this.projects.getAllProjectsFromAPI().subscribe( 
  data => this.test = JSON.stringify( data )
);
// this line is synchronous
console.log( this.test );

在异步块中执行代码:

this.projects.getAllProjectsFromAPI().subscribe(data => { 
  this.test = JSON.stringify(data);
  console.log(this.test)
});

请注意,我添加了 {} 以便在可观察的回调中执行多行.

Note that I added {} in order to execute multiple lines in the observable callback.

这篇关于将API中的数据存储在变量[Angular]中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆