我正在尝试使用我的身份验证服务获取用户令牌,然后使用效果文件中的令牌发出http请求,然后发送另一个操作。但它一直给我这个错误(动作)=> 。我是新手,Angular非常感谢你的帮助!
类型的参数'(动作:[动作,状态])=>空隙'不能分配给'类型的参数(值:[动作,状态],索引:数字)=> ObservableInput< {}>&#39 ;. 键入' void'不能分配给' ObservableInput< {}>'。
import { Injectable } from '@angular/core';
import { Actions, Effect, ofType } from '@ngrx/effects';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/withLatestFrom';
import { HttpClient, HttpRequest } from '@angular/common/http';
import { Store, Action } from '@ngrx/store';
import { tap, mergeMap, map } from 'rxjs/operators';
import { Observable } from 'rxjs/Observable';
import * as PropertyActions from '../actions/property.actions';
//import { Recipe } from '../recipe.model';
import * as fromPropertyReducer from '../reducers/property.reducer';
import * as fromApp from '../store/app.reducer';
import { AuthService } from '../user/auth.service';
@Injectable()
export class PropertyEffects {
constructor(
private actions$: Actions,
private httpClient: HttpClient,
private store: Store<fromApp.AppState>,
private authService: AuthService
){}
@Effect()
sendMessage(): void {
// POST
this.actions$//.pipe(
.ofType(PropertyActions.FETCH_ALL_PROPERTIES)
.withLatestFrom(this.store.select('propertyState'))
.switchMap((action) => {
this.authService.getAuthenticatedUser().getSession((err, session) => {
if (err) {
return;
}
const req = new HttpRequest('POST', 'https://yxalbf1t6l.execute-api.us-east-1.amazonaws.com/dev/todos',
//state.properties,
{ "text": "Testing10", "checked": true, "properties": [{"c":6},{"b":7}] },
{reportProgress: true},
);
return this.httpClient.request(req)
}).pipe(
// If successful, dispatch success action with result
map(data => {
console.log(`Success ${JSON.stringify(data)}, 0, 2)`);
//return { type: PropertyActions.OPEN_ALL_PROPERTIES, payload: data }
//return { type: 'LOGIN_SUCCESS', payload: data }
return new PropertyActions.OpenAllProperties(data)
})
)
})
}
&#13;
然后我的第二个问题是我想要在http请求中插入标题,但使用httpclient。怎么做
this.http.post('https://API_ID.execute-api.REGION.amazonaws.com/dev/compare-yourself', data, {
headers: new Headers({'Authorization': session.getIdToken().getJwtToken()})
})
&#13;
答案 0 :(得分:1)
您需要从效果中调度动作。因此,指定 void 的返回值不是有效选项,除非您明确指示ngrx您不想返回操作。
从文档中,“使用@Effect()装饰器修饰的Observables应该是要调度的动作流。将{dispatch:false}传递给装饰器以防止调度操作。”
请从ngrx documentation查看此示例。
class MyEffects {
constructor(private actions$: Actions, private auth: AuthService) { }
@Effect() login$: Observable<Action> = this.actions$
.ofType('LOGIN')
.switchMap(action =>
this.auth.login(action.payload)
.map(res => ({ type: 'LOGIN_SUCCESS', payload: res }))
.catch(err => Observable.of({ type: 'LOGIN_FAILURE', payload: err }))
);
@Effect() logout(): Observable<Action> {
return this.actions$
.ofType('LOGOUT')
.switchMap(() =>
this.auth.logout()
.map(res => ({ type: 'LOGOUT_SUCCESS', payload: res }))
.catch(err => Observable.of({ type: 'LOGOUT_FAILURE', payload: err }))
);
}
}