收到错误类型 'Observable<{}>' is not assignable to type 'Observable<User>'。当尝试使用 @ngrx/store 的 store.select()

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

我试图在 API 调用后设置我的 $currentUser,但我一直收到错误消息:

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

我抛出错误的组件如下所示:

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();
  }
}

我的效果是这样的::

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' })
      ));
}

您应该更改构造函数并将依赖项设置为 Store as public store: Store<User>。或者你真的需要它像 Store<AppState> 那样吗?应该使用泛型自动设置类型 src/operator/select.ts:

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

或者,抛出错误是因为您将 $currentUser 定义为:

$currentUser: Observable<User>;

所以你可以在将数据分配给this.$currentUser时使用type assertion in TypeScript:

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