0

I am just trying to mock up my http calls with a simple BehaviorSubject and an Observable properties in my resolver service. I do not understand why the following is not working:

schedule-administration.service.ts:

@Injectable({
  providedIn: 'root'
})
export class ScheduleAdministrationService implements OnInit, Resolve<Observable<SportType[]>> {
  private _sportTypesSubject = new BehaviorSubject<SportType[]>([]);
  sportTypes$: Observable<SportType[]> = this._sportTypesSubject.asObservable();  

  constructor(private leagueAdminService: LeagueAdministrationService) {}

  resolve(): Observable<SportType[]> | Observable<Observable<SportType[]>> | Promise<Observable<SportType[]>> {
    this._sportTypesSubject.next([...])
    return this.sportTypes$;    
  }
}

I thought that the resolve method is supposed to subscribe to the returned observable? When I manually do this.sportTypes$.subscribe(v => console.log(v)) it correctly logs the values....

1 Answer 1

1

The Problem by your construct is that you initially use a BehaviorSubject. The Angular Router expect the result of your Resolver to be completed before return data. So Using BehaviorSubject assume that you have only one value at a time, but the value can always change.

To Make this work i think you can only take the first emitted response/value e.g using the first operator:

resolve(): Observable<SportType[]> | Observable<Observable<SportType[]>> | Promise<Observable<SportType[]>> {
    return this._sportTypesSubject.asObservable().pipe(first())    
}

According to the Angular documentation

A data provider class can be used with the router to resolve data during navigation. The interface defines a resolve() method that will be invoked when the navigation starts. The router will then wait for the data to be resolved before the route is finally activated.

Sign up to request clarification or add additional context in comments.

3 Comments

hmm interesting, but if I were to be using http.get() I would be retrieving a list of all of the SportTypes not just the first one, any idea how to make it work with all of them?
@O.MeeKoh it isn't taking the first item, but the first response
@Drenai yeah, definitely, I completely missed that part, since a single response is a an entire list at a time. So see that it works now using return this._sportTypesSubject.asObservable().pipe(first<SportType[]>()) I had to specify the type. But I'm still a little hazy as to why it didnt work before. Any chance you can add a little more detail in the answer. Does resolver expect the observable that is returned to be completed and not to emit any more values? Sorry i just want to make sure I understand it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.