2016-09-17 73 views
0

我想我$currentUser API調用後設置的,但我不斷收到錯誤時:獲取錯誤類型'Observable <{}>'不可分配爲鍵入'Observable <User>'。試圖用@ NGRX /存儲的store.select()

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

升級到angular-cli beta 14後,我得到了同樣的錯誤 –

+0

我也是使用Angular-cli,但仍然在Webpack上。 8 – cport1

回答

2

你應該改變你的構造函數,並設置依賴性以專賣店爲public store: Store<User>。或者你真的需要它作爲Store<AppState>?該類型應該會自動使用泛型src/operator/select.ts設置:

$currentUser: Observable<User>; 

這樣你就可以將數據分配給this.$currentUser時使用type assertion in TypeScript

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

或者,因爲你定義$currentUser作爲引發錯誤

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