【问题标题】:user of Angular 5 service in ngrx effectngrx 效果中 Angular 5 服务的用户
【发布时间】:2018-03-12 11:24:35
【问题描述】:

我正在尝试使用我的身份验证服务来获取用户令牌,然后使用我的效果文件中的令牌发出 http 请求,然后发送另一个操作。但它一直在 (action) => 上给我这个错误。我是效果和 Angular 的新手,非常感谢您的帮助!

'(action: [Action, State]) => void' 类型的参数不能分配给'(value: [Action, State], index: number) => ObservableInput' 类型的参数。 类型 '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)
                    })
            )
        })
}

然后我的第二个问题是我想像在 http 请求中一样插入标头,但使用 httpclient。如何做到这一点

this.http.post('https://API_ID.execute-api.REGION.amazonaws.com/dev/compare-yourself', data, {
        headers: new Headers({'Authorization': session.getIdToken().getJwtToken()})
      })

【问题讨论】:

    标签: angular angular-services ngrx ngrx-effects


    【解决方案1】:

    您需要从效果中调度一个动作。因此,指定返回 void 不是有效选项,除非您明确指示 ngrx 您不想返回操作。

    从文档中,“用 @Effect() 装饰器装饰的 Observable 应该是要调度的动作流。将 { 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 }))
          );
      }
    }
    

    【讨论】:

    • 感谢拉丁语!这正是我所需要的。但是,如果您能帮助澄清一件事:有什么区别,为什么登录是分配形式的,而注销是作为函数编写的?
    • 它们的写法相同,但一个在 lambda 中带一个参数,另一个不带。所以你可以把第一个写成 (action) => this.auth.login(action.payload)。问题的症结在于登录在Action构造函数中带了一个参数,而注销没有。希望有帮助。 :)
    猜你喜欢
    • 1970-01-01
    • 2020-02-14
    • 1970-01-01
    • 2020-01-20
    • 2018-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多