Home > Software design >  Angular http client subscribe
Angular http client subscribe

Time:06-11

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$;
  }

CodePudding user response:

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>

CodePudding user response:

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>

  • Related