Angular 2 - Checking for server errors from subscribe

前端 未结 2 1436
南笙
南笙 2020-12-08 00:18

I feel like this scenario should be in the Angular 2 docs, but I can\'t find it anywhere.

Here\'s the scenario

  1. submit a form (create object) that is i
相关标签:
2条回答
  • 2020-12-08 00:35

    You can achieve with following way

        this.projectService.create(project)
        .subscribe(
            result => {
             console.log(result);
            },
            error => {
                console.log(error);
                this.errors = error
            }
        ); 
    }
    
    if (!this.errors) {
        //route to new page
    }
    
    0 讨论(0)
  • 2020-12-08 00:41

    As stated in the relevant RxJS documentation, the .subscribe() method can take a third argument that is called on completion if there are no errors.

    For reference:

    1. [onNext] (Function): Function to invoke for each element in the observable sequence.
    2. [onError] (Function): Function to invoke upon exceptional termination of the observable sequence.
    3. [onCompleted] (Function): Function to invoke upon graceful termination of the observable sequence.

    Therefore you can handle your routing logic in the onCompleted callback since it will be called upon graceful termination (which implies that there won't be any errors when it is called).

    this.httpService.makeRequest()
        .subscribe(
          result => {
            // Handle result
            console.log(result)
          },
          error => {
            this.errors = error;
          },
          () => {
            // 'onCompleted' callback.
            // No errors, route to new page here
          }
        );
    

    As a side note, there is also a .finally() method which is called on completion regardless of the success/failure of the call. This may be helpful in scenarios where you always want to execute certain logic after an HTTP request regardless of the result (i.e., for logging purposes or for some UI interaction such as showing a modal).

    Rx.Observable.prototype.finally(action)

    Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.

    For instance, here is a basic example:

    import { Observable } from 'rxjs/Rx';
    import 'rxjs/add/operator/finally';
    
    // ...
    
    this.httpService.getRequest()
        .finally(() => {
          // Execute after graceful or exceptionally termination
          console.log('Handle logging logic...');
        })
        .subscribe (
          result => {
            // Handle result
            console.log(result)
          },
          error => {
            this.errors = error;
          },
          () => {
            // No errors, route to new page
          }
        );
    
    0 讨论(0)
提交回复
热议问题