我正在尝试在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' })
));
}
答案 0 :(得分:2)
您应该更改构造函数并将依赖关系设置为Store var list = JsonConvert.SerializeObject(Yourmodel,
Formatting.None,
new JsonSerializerSettings() {
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
});
return list;
。或者你真的需要它作为public store: Store<User>
吗?应使用泛型src/operator/select.ts
自动设置类型:
Store<AppState>
或者,抛出错误是因为您将constructor(
userService: UserService,
public store: Store<User>
) {
this.userService = userService;
this.$currentUser = this.store.select('user');
}
定义为:
$currentUser
因此您可以在将数据分配到$currentUser: Observable<User>;
时使用type assertion in TypeScript:
this.$currentUser