订阅中的多个请求问题

Problem with multiple request in subscribe

我在我的组件上调用一个方法,该方法通过在输入中输入的邮政编码加载地址信息。 首先,我调用将信息加载到 getAddress$ 变量的方法,然后订阅它以获取数据并将其分配给表单输入。 在第一页加载时,它只在 api 中执行一个调用,但当我通知另一个邮政编码时,我的订阅将再添加一个 return,对 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();
        });
    }
}

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 调用的过滤器之后被调用。

您确定第一张地图会生效吗?我想第一张地图可能会有地址。

您不需要在每个 blur 事件中添加到 this.subscriptions。相反,您可以在 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, ''));
    }
  }