0

I am very new in angular. I am trying to call my web API method from angular. I am getting an message loading... on my browser when I do the http.get request . I am assuming there is an error at http.get Below is my code

 getProjectDetails() {

    return this._http.get(this.myAppUrl + 'api/AllItProjectsLists/Index').pipe(map(
      response => {
        return response;
      }));

  }

I tried to trap the error by implementing handlerror in angular

 private handleError(operation: String) {
    return (err: any) => {
      let errMsg = `error in ${operation}() retrieving ${this.myAppUrl}`;
      console.log(`${errMsg}:`, err)
      if (err instanceof HttpErrorResponse) {
        // you could extract more info about the error if you want, e.g.:
        console.log(`status: ${err.status}, ${err.statusText}`);
        // errMsg = ...
      }
      return Observable.throw(errMsg);
    }
  }

not sure, how to implement it in my method getProjectDetails()

Below is my entire code:

import { Injectable, Inject } from '@angular/core';
import { HttpClient, HttpInterceptor, HttpErrorResponse } from '@angular/common/http';
import { map } from 'rxjs/operators';
import { AllItProject } from '../../models/allitproject';
import { Observable } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';



@Injectable({
  providedIn: 'root'
})
export class ProjectDetailService {

  myAppUrl = '';

  constructor(private _http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
    this.myAppUrl = baseUrl;
  }

  private handleError(operation: String) {
    return (err: any) => {
      let errMsg = `error in ${operation}() retrieving ${this.myAppUrl}`;
      console.log(`${errMsg}:`, err)
      if (err instanceof HttpErrorResponse) {
        // you could extract more info about the error if you want, e.g.:
        console.log(`status: ${err.status}, ${err.statusText}`);
        // errMsg = ...
      }
      return Observable.throw(errMsg);
    }
  }


  getProjectDetails() {

    return this._http.get(this.myAppUrl + 'api/AllItProjectsLists/Index').pipe(map(
      response => {
        return response;
      }));

  }

The error is coming somewhere when I do http.get. When I open the developers tools in the browser, I see the error :

"Http failure response for https://localhost:44313/api/AllItProjectsLists/Index: 500 OK".

Below is my controller method that I am trying to call

namespace ProjectDetails.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AllItProjectsListsController : ControllerBase
    {
        private readonly KPIContext _context;
        private readonly IProject objProject;

        public AllItProjectsListsController(IProject _objProject)
        {
            objProject = _objProject;

        }


        [HttpGet("Index")]
        public IEnumerable<AllItProjectsList> Index()
        {
            return objProject.GetAllProjectDetails();
        }

any help will be highly appreciated.

6
  • 1
    Note that .pipe(map(response => response)) is pointless. Commented Sep 23, 2019 at 18:04
  • are you sure you need /index? Commented Sep 23, 2019 at 18:04
  • I am learning angular by follwoing a tutorial and that person who wrote the article is using ..pipe(map( response => { return response; what else can I use. I also put my.net core controller class above to show which index method, i am trying to call. Commented Sep 23, 2019 at 18:08
  • Try [HttpGet("/Index")] or [Route("Index")] in your controller. Commented Sep 23, 2019 at 18:16
  • Try to debug your code. What happens if you navigate to https://localhost:44313/api/AllItProjectsLists/Index in the browser? Do you get a response with data or a 500? Commented Sep 23, 2019 at 18:46

3 Answers 3

1

If you would like to see your error, you can use catchError to trap that, modify your service like the following :

import { Injectable, Inject } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { tap, catchError } from 'rxjs/operators';

@Injectable()
export class ProjectDetailService {

  myAppUrl = '';

  constructor(private _http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
    this.myAppUrl = baseUrl;
  }

  getProjectDetails() {
    return this._http.get(this.myAppUrl + 'api/AllItProjectsLists/Index', this.setHttpHeader())
      .pipe(
        tap(data => console.log("Anlagenstatus Daten:", data)),
        catchError(this.handleError),
      )
  }

  private setHttpHeader() {
    const headers = new HttpHeaders().set('Accept', 'application/json').set('Content-Type', 'application/json');
    let options = { headers: headers };
    return options;
  }

  private handleError(error: Response): Observable<any> {
    console.error("observable error: ", error);
    return Observable.throw(error.statusText);
  }

}

Now you can see your error in the browser -> console tab

If you got an error with status code 500: It means there is an error in your server (Inspect your API)

Sign up to request clarification or add additional context in comments.

4 Comments

I am getting an error "Cannot find name RequestOptions"
I am getting an error on both options and map saying "cannot find name options" and Property map does not exists on type observable.
@Anjali - look at this example: stackblitz.com/edit/angular-crahu8 (in the root of the project there is a service named ProjectDetailService)
Thank You. I am getting the error on the server side, but your error catching works perfectly.
1

If you are getting internal server that means angular's httpclient able to hit the server but due to some issue in your server code... Server giving 500 Internal server error...

I would suggest you to verify your API using POST man tool... It will help you clear weather it's a server side code issue or angular side...

Moreover, use Angular "observable" and "Subscribe" feature which help you get this fix quickly.

    /** GET heroes from the server */
getHeroes (): Observable<Hero[]> {
  return this.http.get<Hero[]>(this.heroesUrl)
}

For more details please follow the below link

https://angular.io/tutorial/toh-pt6

Let me know if you still facing the same issue...

Comments

0
  1. Are these constructor level injection registered somewhere or you are just injecting without any registration tool... like autofac, ninject etc.

  2. Remove routing and all from API method or make a simple get method without any parameters and then hit the API from POSTMAN.

I hope this time you will definitely get your solution...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.