Search code examples
angulartypescriptrxjsngrxrxjs5

Getting the error Type 'Observable<{}>' is not assignable to type 'Observable<User>'. when trying to use @ngrx/store's store.select()


I am trying to set my $currentUser after an API call, but I keep getting the error:

[default] 
Type 'Observable<{}>' is not assignable to type 'Observable<User>'.
  Type '{}' is not assignable to type 'User'.
    Property 'username' is missing in type '{}'.

My component that's throwing the error looks like this:

import {Component, state} from '@angular/core';
import { Observable } from "rxjs";

import { User } from '../../../../models/user';
import { Store } from '@ngrx/store';
import { AppState } from '../../../../reducers';
import {UserService} from "../../../../services/user.service";

@Component({
  selector: 'user-center',
  templateUrl: 'user-center.component.html',
  styleUrls: ['user-center.component.scss']
})
export class UserCenter {
  $currentUser: Observable<User>;
  userService: UserService;
  constructor(
    userService: UserService,
    public store: Store<AppState>
  ) {
    this.userService = userService;
    this.$currentUser = this.store.select('user');
  }

  ngOnInit() {
    this.userService.initialise();
  }
}

My Effect looks like this::

import { Injectable } from '@angular/core';
import { Effect, StateUpdates, toPayload } from '@ngrx/effects';
import { Observable } from 'rxjs/Observable';

import { AppState } from '../reducers';
import { UserService } from '../services/user.service';
import { UserActions } from "../actions/UserActions";

@Injectable()
export class UserEffects {
  constructor(
    private updates$: StateUpdates<AppState>,
    private userService: UserService,
    private userActions: UserActions,
  ) {}


  @Effect() CurrentUser$ = this.updates$
    .whenAction('INIT_USER')
    .switchMap(() => this.userService.getUser()
      .map(user => this.userActions.setCurrentUser(user))
      .catch(() => Observable.of({ type: 'GET_USER_FAILED' })
      ));
}

Solution

  • You should change your constructor and set dependency to Store as public store: Store<User>. Or do you really need it to be as Store<AppState>? The type should be set automatically using generics src/operator/select.ts:

    constructor(
        userService: UserService,
        public store: Store<User>
    ) {
        this.userService = userService;
        this.$currentUser = this.store.select('user');
    }
    

    Alternatively, the error is thrown because you define $currentUser as:

    $currentUser: Observable<User>;
    

    so you can use type assertion in TypeScript when assigning the data to this.$currentUser:

    this.$currentUser = <Observable<User>>this.store.select('user');