我有一项可从API获取数据的服务:https://jsonplaceholder.typicode.com/posts/1
但是我不能在变量中存储数据
代码: 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
constructor( private projects : ProjetsService ) { }
ngOnInit() {
this.projects.getAllProjectsFromAPI().subscribe( data => this.test = JSON.stringify( data ) );
console.log( this.test );
}
我尝试对var进行控制台测试,但未定义
答案 0 :(得分:1)
您正在尝试记录尚未计算的值。
// 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)
});
请注意,我添加了{}
以便在可观察的回调中执行多行。