订阅中有多个请求的问题

时间:2019-09-10 14:09:08

标签: angular ngrx-store ngrx-effects

我正在我的组件上调用一个方法,该方法通过在输入中输入的邮政编码来加载地址信息。 首先,我调用将信息加载到getAddress $变量中的方法,然后订阅该方法以获取数据并将其分配给表单输入。 在第一页加载时,它仅在api中执行一个调用,但是当我通知另一个邮政编码时,我的订阅将添加一个返回值,从而对该api进行了多个调用。 我想要做的是输入的每个邮政编码,每个邮政编码只给我1个结果。 下面是我的代码,该方法在输入模糊事件上触发。 我已经实现了本文https://blog.angularindepth.com/the-best-way-to-unsubscribe-rxjs-observable-in-the-angular-applications-d8f9aa42f6a0中包含的所有失败的解决方案 您能帮我解决这个问题吗?我在做什么错了?

谢谢!

// class CommonEffect

@Injectable()
export class CommonEffect {
    constructor(private actions$: Actions,
        private authApi: CommonService) {
    }
    @Effect()
    getAddress$: Observable<Action> = this.actions$
        .pipe(
            ofType(actions.ActionTypes.GET_ADDRESS),
            map((action: actions.GetAddress) => action.payload),
            switchMap((state) => {
                return this.authApi.getAddress(state)
                    .pipe(
                        map((address) => new actions.GetAddressSuccess(address)),
                        catchError(error => of(new actions.GetAddressFail(error)))
                    );
            })
        );
}



// function reducer

export function reducer(state = initialState, { type, payload }: any): CommonState {

    if (!type) {

        return state;
    }
    switch (type) {
        case actions.ActionTypes.GET_ADDRESS:
            {

                return Object.assign({}, state, {
                    getAddressLoading: true,
                    getAddressLoaded: false,
                    getAddressFailed: false,
                });
            }

        case actions.ActionTypes.GET_ADDRESS_SUCCESS: {
            const tempAddress = new SearchAddressModel(payload.data);
            return Object.assign({}, state, {
                address: tempAddress,
                getAddressLoading: false,
                getAddressLoaded: true,
                getAddressFailed: false,
            });
        }
        case actions.ActionTypes.GET_ADDRESS_FAIL:
            {
                return Object.assign({}, state, {
                    getAddressLoading: false,
                    getAddressLoaded: true,
                    getAddressFailed: true,
                });
            }

        default: {
            return state;
        }
    }
}

// class CommonSandbox

@Injectable()
export class CommonSandbox {

    /* get address*/
    public getAddress$ = this.appState$.select(getAddress);
    public addressLoading$ = this.appState$.select(addressLoading);
    public addressLoaded$ = this.appState$.select(addressLoaded);
    public addressFailed$ = this.appState$.select(addressFailed);

    constructor(private router: Router,
        protected appState$: Store<store.AppState>,
    ) {
    }
    public getAddress(params) : void {
        this.appState$.dispatch(new commonAction.GetAddress(params));
    }

}

// class component

export class AddaddressesComponent implements OnInit, OnDestroy {

    addAddressForm: FormGroup;
    addressId: any;
    openAddress = false;
    private subscriptions: Array<Subscription> = [];

    constructor(private route: ActivatedRoute, private router: Router, public formBuilder: FormBuilder, public snackBar: MatSnackBar, public commonSandbox: CommonSandbox, public accountSandbox: AccountSandbox) {
    }

    ngOnInit() {
        this.addressId = this.route.snapshot.paramMap.get('id');
        this.addAddressForm = this.formBuilder.group({
            'firstName': ['', Validators.required],
            'lastName': ['', Validators.required],
            'address': ['', Validators.required],
            'phoneNumber': '',
            'phoneMobileNumber': ['', Validators.required],
            'complement': '',
            'reference': '',
            'addresstype': '',
            'city': ['', Validators.required],
            'zone': ['', Validators.required],
            'state': ['', Validators.required],
            'postalcode': ['', Validators.required]
        });
        this.addAddressForm.patchValue({ addresstype: '1', tc: true });

    }

    // method (blur) search address for postalcode
    public getSeacrhAddress(value: any) {
        if (value) {

            // Here I call the api that returns the address according to the postalcode entered, below I retrieve the value through subscribe.
            this.commonSandbox.getAddress(value.replace(/[^\d]+/g, ''));

            // the subscribe address parameter in the first pass on the first page load is undefined, as I inform another postalcode it always has the previous value
            this.subscriptions.push(this.commonSandbox.getAddress$.subscribe(address => {
               //With the breakpoint here, each postalcode you enter will increment one more pass instead of just once.
                if (address) {
                    this.addAddressForm.controls['address'].setValue(address.logradouro);
                    this.addAddressForm.controls['city'].setValue(address.localidade);
                    this.addAddressForm.controls['zone'].setValue(address.bairro);
                    this.addAddressForm.controls['state'].setValue(address.uf);
                    this.openAddress = true;
                }
            }));
        }
    }

    // destroy the subscribed events while page destroy
    ngOnDestroy() {
        this.subscriptions.forEach(each => {
            each.unsubscribe();
        });
    }
}

2 个答案:

答案 0 :(得分:0)

take(1)应该可以工作,但是放置它的位置很重要。 我没有测试以下代码,但我认为这对您有用:

@Effect()
getAddress$: Observable<Action> = this.actions$
  .pipe(
    ofType(actions.ActionTypes.GET_ADDRESS),
    take(1),
    map((action: actions.GetAddress) => action.payload),
    switchMap((state) => {
      return this.authApi.getAddress(state)
        .pipe(
          take(1)
          map((address) => new actions.GetAddressSuccess(address)),
          catchError(error => of(new actions.GetAddressFail(error)))
        );
    })
  );

请注意,take(1)仅在第一次getAddress调用的过滤器之后被调用。

您确定第一张地图会生效吗?我认为第一张地图可能会得到地址。

答案 1 :(得分:0)

您不需要在每个this.subscriptions事件中添加到blur。相反,您可以在ngOnInit中订阅一次。

ngOnInit() {
    this.addressId = this.route.snapshot.paramMap.get('id');
    this.addAddressForm = this.formBuilder.group({
      'firstName': ['', Validators.required],
      'lastName': ['', Validators.required],
      'address': ['', Validators.required],
      'phoneNumber': '',
      'phoneMobileNumber': ['', Validators.required],
      'complement': '',
      'reference': '',
      'addresstype': '',
      'city': ['', Validators.required],
      'zone': ['', Validators.required],
      'state': ['', Validators.required],
      'postalcode': ['', Validators.required]
    });
    this.addAddressForm.patchValue({ addresstype: '1', tc: true });

// the subscribe address parameter in the first pass on the first page load is undefined, as I inform another postalcode it always has the previous value
    this.subscriptions.push(this.commonSandbox.getAddress$.subscribe(address => {
      //With the breakpoint here, each postalcode you enter will increment one more pass instead of just once.
      if (address) {
        this.addAddressForm.controls['address'].setValue(address.logradouro);
        this.addAddressForm.controls['city'].setValue(address.localidade);
        this.addAddressForm.controls['zone'].setValue(address.bairro);
        this.addAddressForm.controls['state'].setValue(address.uf);
        this.openAddress = true;
      }
    }));

  }

  // method (blur) search address for postalcode
  public getSeacrhAddress(value: any) {
    if (value) {

      // Here I call the api that returns the address according to the postalcode entered, below I retrieve the value through subscribe.
      this.commonSandbox.getAddress(value.replace(/[^\d]+/g, ''));
    }
  }