[http] Angular 2 - Checking for server errors from subscribe

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 invalid on the server
  2. server returns a 400 bad request with errors I display on the form
  3. after the subscribe comes back, I want to check an error variable or something (ie. if no errors > then route to newly created detail page)

I imagine it working something like this:

this.projectService.create(project)
    .subscribe(
        result => console.log(result),
        error => {
            this.errors = error
        }
    ); 
}

if (!this.errors) {
    //route to new page
}

I'm very new to Angular 2 so this may come from my lack of understanding in how an Observable works. I have no issue with displaying that data on the form, but can't figure out how to see it within the ts component. I really just want to check the success/fail of the http create.

This question is related to http angular subscribe

The answer is


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
}

Examples related to http

Access blocked by CORS policy: Response to preflight request doesn't pass access control check Axios Delete request with body and headers? Read response headers from API response - Angular 5 + TypeScript Android 8: Cleartext HTTP traffic not permitted Angular 4 HttpClient Query Parameters Load json from local file with http.get() in angular 2 Angular 2: How to access an HTTP response body? What is HTTP "Host" header? Golang read request body Angular 2 - Checking for server errors from subscribe

Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Examples related to subscribe

Angular 2: How to call a function after get a response from subscribe http.post Angular 2 - Checking for server errors from subscribe