简体   繁体   中英

Angular call service for save data

I have a form that creates a user and if it already exists in base, I have an error that is returned and I open a popup

My Service:

  data$ = new BehaviorSubject({
    userList: {},
    user: {},
    create: ''
  });
  
  dispatch(action: Action): Observable<true | { error: string; }> {
    switch (action.type) {
      case ActionTypes.USER_GET_LIST:
        this.getUsers(action.payload);
        return of(true);
      case ActionTypes.USER_CREATE:
        this.createUser(action.payload);
        return of(true);
    }
  }

  private createUser(user: User){
    this.http.post{body : user})
    .subscribe(
        message => this.data$.next({...this.data$.value, create: message}),
        error => {
          this.data$.error(error)
          if (error.error?.title === 'CustomException' && error.status === 400) {
            //OPEN POPUP
            return throwError(error);
          } else {
            return throwError(error);
          }   
        }
    ); 
  }

I call service in my component:

this.userService.dispatch({ type: ActionTypes.USER_CREATE, payload: user });
this.userService.data$.asObservable();
this.router.navigate(['/users/user/list']);

My problem is that it goes directly to the list page and if there is an error the one if is displayed on the list page. I want to wait for the return and be redirected only if there is no error

There are several issues with the code:

a1) this.userService.data$.asObservable();

This does nothing. ...data$.asObservable(); returns an Observable of your BehaviourSubject, but you don't assign it to a variable or use it any other way. Hard to say what this meant to do.

a2) this.userService.dispatch({ type: ActionTypes.USER_CREATE, payload: user });

This also returns an Observable that is neither assigned nor used.

a1) and a2) are the reason why your code rushes onward to this.router.navigate(['/users/user/list']); . But until then the http request is not finished yet, and whatever you wanted to achieve with a1) has not happend.

b) switch (action.type) {... }

You call functions in your switch which have async behaviour. But you immediatly return an Observable<boolean> without waiting for the createUser / getUsers to finish.

c) generic comment:

It looks like if you are getting started with Observables, ngrx, and rxjs.

From my experience i would recommend first getting familiar with Observables - or other async stuff.

Then look into how rxjs allows you to work with Observables by using.pipe() and rxjs/operators.

Finally have a look at ngrx. Your dispatch function does stuff that would perfectly fit ngrx/effects, if you pipe'd inside createUser instead of subscribing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM