简体   繁体   中英

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. The implementation of the get request is

 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.

* However, in my html template I am not getting the schedule$ variables set. Can anyone help me with setting this up so that the schedule$ array is saved and accessible by the ngFor.

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

 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 .

So, it's no longer an observable. Change to

schedules: Schedule[] = [];

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM