簡體   English   中英

獲取錯誤類型“Observable&lt;{}&gt;”不可分配給類型“Observable”<User> &#39;。 嘗試使用@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在 TypeScript 中使用類型斷言

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM