我遇到了向后端执行简单get请求的问题,后端返回了JSON。当我在我的代码中执行此get请求时,它返回一个observable,我通过subscribe方法直接分配给一个变量。但是,它只能在此方法中使用并且在其他任何地方都未定义。
api服务获取方法:
public getAllProcessCategories() {
return this.http.get(this.apiURL + 'typeOne=PROCESSCATEGORIES&typeTwo=PROCESSCATEGORIES');
}
api的用法:
import { ApiService } from './../api.service';
import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { ProcessCategory } from './process-category';
@Component({
selector: 'app-process-category',
templateUrl: './process-category.component.html',
styleUrls: ['./process-category.component.css']
})
export class ProcessCategoryComponent implements OnInit {
processCategories = [];
constructor(private api: ApiService) {
}
ngOnInit(): void {
this.fillProcessCategories();
this.printAfterRequest();
}
fillProcessCategories() {
this.api.getAllProcessCategories().subscribe(data => {
this.processCategories = data['entities'];
console.log(this.processCategories);
});
}
printAfterRequest() {
for (const category of this.processCategories) {
console.log(category);
}
}
}
我知道它是,因为我想在httpRequest完成之前得到结果。那么在angular 4中执行get请求的最佳方法是什么,它返回一个JSON,然后解析这个JSON并将其映射到一个类以便在我的组件中使用?
答案 0 :(得分:1)
稍微调整您的API方法
return this.http.get(this.apiURL+ 'typeOne=PROCESSCATEGORIES&typeTwo=PROCESSCATEGORIES')
.map(res => {
return res.json();
})
.catch(this.handleError);
然后移动printAfterRequest
以订阅回调
fillProcessCategories() {
this.api.getAllProcessCategories().subscribe(data => {
this.processCategories = data['entities'];
this.printAfterRequest();
console.log(this.processCategories);
});
}