-2

I have a Clip Service:

export class ClipService {

    allClips: Clip[] = [];
    private clips = new BehaviorSubject<Clip[]>(null);

    constructor(private http: HttpClient) {
        this.loadClips();
    }

    private fetchClips(body?: string): Observable<Clip[]> {
        let url = myurl/clips;
        try {
            return this.http.get<Clip[]>(url);
        } catch (e) {
            console.error('Error fetching clips: ' + e);
        }
        
    }

    loadClips(): void {
        this.fetchclips().subscribe(allClips => this.allClips = allClips);
        this.setClips(this.allClips);
    }

    getClips(): Observable<Clip[]> {
        return this.clips.asObservable();
    }
}

and a ClipComponent.ts where I cosume the service like this:

ngOnInit(): void {
    this.clipService.getClips().subscribe(clips => {
        this.allClips = clips;
        this.clips = this.allClips;

        console.log(this.clips);
        this.populateFilters(this.clips);
    });
}

Even though a call to the API is triggered and there are around 200 clips returned, the console.log in the component always logs an empty array.

What am I missing here?

Sebastian M
  • 471
  • 1
  • 4
  • 20

1 Answers1

2
  1. The variable this.allClips is assigned asynchronously in the service. So any statements that directly depend on it must be inside the subscription. By the time you're doing this.setClips(this.allClips); it still holds the previous value or undefined.
loadClips(): void {
  this.fetchclips().subscribe(allClips => {
    this.allClips = allClips;
    this.setClips(this.allClips);
  });
}

You could find more info about asynchronous data here.

  1. If you're initializing the BehaviourSubject with null, you could as well use ReplaySubject with buffer 1. It serves the same purpose as the BehaviorSubject except it doesn't need a default value (so you don't have to deal with the initial null) and it doesn't have the BehaviorSubject's synchronous getValue() function.
private clips = new ReplaySubject<Clip[]>(1);
ruth
  • 29,535
  • 4
  • 30
  • 57