我希望通过推送新的评级值更新 姐妹对象的评分(这是一个数字数组)到收视率阵列。更新实际上有效,但没有重新加载页面,我看到发送值的两倍,来自状态。 因此,我认为问题在于更新状态中的数组, reducer 或我在史诗函数中接收结果的方式。
my rate-sitter.ts:
rateSitter(filledStars) {
let rating = filledStars;
let sitter: Sitter = this.sitter as Sitter;
this.usersActions.rateSitter(sitter, rating)
}
my users.actions.ts:
rateSitter(sitter: Sitter, rating: number): void {
console.log(sitter);
console.log(rating);
this.ngRedux.dispatch({
type: UsersActions.RATE_SITTER,
payload: { sitter, rating }
});
}
我的users.epic.ts:
rateSitter = (action$: ActionsObservable<any>) => {
return action$.ofType(UsersActions.RATE_SITTER) // Listen for this action
.mergeMap(({ payload }) => { // payload: (subject: Subject, date: Date): When this action is activated, call ws through service class or directly like below
return this.usersService.rateSitter(payload.sitter, payload.rating)
.map((result) => ({ // when web service responds with success, call this action with payload that came back from webservice
type: UsersActions.RATED_SITTER,
payload: payload // Hack: Db contains all data, not just yours.
}))
.catch(error => Observable.of({ // when web service responds with failure, call this action with payload that came back from webservice
type: UsersActions.FAILED_RATED_SITTER,
payload: error
}));
});
}
我的users.reducer.ts:
case UsersActions.RATE_SITTER:
return state;
case UsersActions.RATED_SITTER:
let indexSitter = state.sitters.findIndex(sitter => { return sitter._id === action.payload.sitter._id });
let newRatings = [...state.sitters[indexSitter].rating, action.payload.rating];
console.log(newRatings);
console.log(indexSitter);
let newSitterObj = Object.assign({}, state.sitters[indexSitter]);
newSitterObj.rating = newRatings;
let newSitters = [...state.sitters.slice(0, indexSitter),
newSitterObj,
...state.sitters.slice(indexSitter + 1)];
console.log(newSitters);
console.log(action.payload)
return tassign(state, { sitters: newSitters });
case UsersActions.FAILED_RATED_SITTER:
return state;
最后是我的users.service.ts
rateSitter(sitter: Sitter, rating: number) {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
//'Authorization': 'my-auth-token' // If you use auth.
})
};
sitter.rating.push(rating)
return this.http.put("http://angular2api2.azurewebsites.net/api/internships/" + sitter._id, sitter, { responseType: 'text' });
}
答案 0 :(得分:2)
我相信它是因为你在user.service.ts中修改你的状态。
通过致电sitter.rating.push
,您可以通过改变将评级添加到您的州。在你的reducer中,你再次添加它,即使它已被添加
如果可能,你应该避免改变状态。
在服务中,您可以代替sitter.rating.push
执行以下操作:
let copy = { ...sitter, rating: [...sitter.rating, rating]}
return this.http.put("http://angular2api2.azurewebsites.net/api/internships/" + copy._id, copy, { responseType: 'text' });
这将创建sitter
的副本,并将评级添加到副本中。