问题描述
我无法从API下载数据
I can't download data from the API
我做错了,但我不知道
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Basic ' + btoa(userPassword)
}),
observe: 'response' as 'body'
};
@Injectable({
providedIn: 'root'
})
export class CoverageService {
eligibilityUrl = nepalehrUrl + 'EligibilityRequest';
constructor(private http: HttpClient) { }
getEligibilityData(body:object): Observable<EligibilityResponse> {
return this.http.post<EligibilityResponse>(this.eligibilityUrl, body, httpOptions);
}
}
我有信息:
组件中的代码
let bodyEligibility = {
resourceType: "EligibilityRequest",
patient: {
reference: "Patient/1975632"
}
};
this.myEligibilityData$ = this.coverageService.getEligibilityData(bodyEligibility);
console.log(JSON.stringify(this.myEligibilityData$))
我做错了事
推荐答案
因此,基本上,您必须先进行订阅
观察,才能使http调用生效.当前,当您执行 console.log
时,可以在浏览器 console
中看到完全可观察的内容.基本上,当执行订阅函数http调用并触发基础 subscribe
函数时,您可以在其中分配 myEligibilityData
So basically you've to subscribe
to observable in order to make the http call in action. Currently when you do console.log
you can see thorough observable inside browser console
. Basically when subscribe to function http call gets executed and underlying subscribe
function get triggered where you can assign the value of myEligibilityData
myEligibilityData;
this.coverageService.getEligibilityData(bodyEligibility).subscribe(data => {
console.log(data);
this.myEligibilityData = data;
});
如果要将此数据直接显示在HTML上,则可以保留现有代码.您不必进行 subscribe
的观察,而可以在HTML上使用 async
管道,它将负责应用 subscribe
并从可观察
.
And if you wanted to display this data directly onto the HTML then you can keep your existing code as is. You don't have to subscribe
observable, instead use async
pipe on HTML, it will take care of apply subscribe
and extract data from the Observable
.
<ng-container *ngIf="myEligibilityData$ | async as myEligibilityData">
{{myEligibilityData | json}}
</ng-container>
这篇关于使用基本身份验证从API发布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!