[英]Angular http client subscribe
In Angular 13, I am using using HttpClient import { HttpClient, HttpHeaders } from '@angular/common/http'
to get data from a Django API in my api.service.ts.在 Angular 13 中,我使用 HttpClient
import { HttpClient, HttpHeaders } from '@angular/common/http'
从我的 api.service.ts 中的 Django API 获取数据。 The implementation of the get request is get请求的实现是
public getCalendar(): Observable<Schedule[]> {
return this.http.get<Schedule[]>(`${this.API_URL}/schedule/`,
{
responseType: 'json',
headers: new HttpHeaders().set('Authorization', `Bearer ${this.auth.accessToken}`)
});
}
I believe that the get request works fine, as the console.log inside the subscribe call prints out out my data array.我相信 get 请求可以正常工作,因为 subscribe 调用中的 console.log 会打印出我的数据数组。
* However, in my html template I am not getting the schedule$ variables set. *但是,在我的 html 模板中,我没有设置 schedule$ 变量。 Can anyone help me with setting this up so that the schedule$ array is saved and accessible by the ngFor.
任何人都可以帮助我进行设置,以便ngFor 保存和访问 schedule$ 数组。
calendar.component.html calendar.component.html
<ul *ngFor="let evnt of schedule$ | async">
<li>Working {{evnt.title}}
</ul>
The interface definition for the data is数据的接口定义是
export interface Schedule {
id: number;
title: string;
start: Date;
end: Date;
created_by: string;
event_skaper: string;
event_booker: string;
}
In my calendar.component.ts在我的 calendar.component.ts
schedule$!: Observable<Schedule[]>;
public getCalendar(): any {
this.apiService.getCalendar().subscribe(
(data: any) => {
this.schedule$ = data;
console.log(this.schedule$);
// return this.schedule$;
})
console.log(this.schedule$);
// return this.schedule$;
}
You have already subscribed the Observable
using this.apiService.getCalendar().subscribe
.你已经使用
this.apiService.getCalendar().subscribe
订阅了Observable
。
So, it's no longer an observable.因此,它不再是可观察的。 Change to
改成
schedules: Schedule[] = [];
html html
<ul *ngFor="let evnt of schedules">
<li>Working {{evnt.title}}</li>
</ul>
If you want to use async pipe in HTML you shouldn't subscribe the observable.如果你想在 HTML 中使用异步管道,你不应该订阅 observable。
Because async pipe does that automatically see the doc因为异步管道会自动查看文档
schedule$!: Observable<Schedule[]>;
ngOnInit(): void {
this.schedule$ = this.apiService.getCalendar().pipe(
// This is just for debug
tap((data)=>console.log(data)));
}
<ul *ngFor="let evnt of schedule$ | async">
<li>Working {{evnt.title}}
</ul>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.