Type mismatch when trying to convert an Observable to a Signal in Angular

43 views Asked by At

I am trying to convert an Observable into a Signal to be returned from the login function.

login(username: string, password: string): Signal<LoginResponse> {
  const sourceObservable: Observable<LoginResponse> =
    this.http.post<LoginResponse>(this.apiUrl + '/login', {username, password})

  let lrp: LoginResponse = LoginResponse.withStatus(ResponseStatus.PENDING)

  return toSignal<LoginResponse>(sourceObservable, {requireSync: true, initialValue: lrp,}
  )
}

In the return statement I use toSignal() that takes a ToSignalOptions object with requireSync set to true, and an initial value. However the compiler is complaining at me that there are no overload matches, because it is expecting an initialValue of type undefined, whereas I am providing a type of LoginResponse. It should be LoginResponse, but the analyser does not like that.

Have I done something wrong I am overlooking?

Here's a shot of the error the IDE is displaying. Error as displayed by the IDE

2

There are 2 answers

3
James Ashok On

Please remove requireSync from the ToSignalOptions

initialValue is allowed only when requireSync is falsy

0
OZ_ On

toSignal() requires injection context, we can't call it wherever we want. If you want to use it like this, provide an injector in params:

class SomeService {
  private readonly http = inject(HttpClient);
  private readonly apiUrl = 'https://api.example.com';
  private readonly injector = inject(Injector);

  login(username: string, password: string): Signal<LoginResponse> {
    const sourceObservable = this.http.post<LoginResponse>(
      this.apiUrl + '/login',
      { username, password }
    );

    const lrp: LoginResponse = LoginResponse.withStatus(ResponseStatus.PENDING);

    return toSignal<LoginResponse>(sourceObservable, {
      injector: this.injector,
      initialValue: lrp,
    });
  }
}