Connecting Angular 6 with a .NET Core API

Seeking assistance with a task I've been working on since morning.

Progress so far:

  1. Managed to bind the list to the UI while retrieving it from Firebase.
  2. Successfully connected to "https://jsonplaceholder.typicode.com" and bound the list to the UI.

Where help is required:

However, struggling to bind the list from .NET Core API to Angular 6.

Note:-

  1. The API is operational as confirmed through postman and swagger testing.
  2. Able to make the API call and receive responses from .NET Core API but unable to map or bind it to my angular variable declared as "any". Seems like there's an issue fetching data from the response.

Attempted multiple examples without success. Below is the code implemented in the angular 6 project:

##ToDoService.ts file code

import { Injectable, Inject } from '@angular/core';
import {environment } from "../../environments/environment"
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

@Injectable()
export class ToDoService {
  myAppUrl: string = environment.url;

  constructor(private _http: HttpClient) {
  }
  getToDoList() {
    return this.GetMethod();
  }  

  GetMethod()  : Observable<any> {
    console.log("called");
       var headers = new HttpHeaders();
       headers.append('Content-Type', 'application/json');
       headers.append('Access-Control-Allow-Origin', '*');
       headers.append('Access-Control-Allow-Methods', '*');
       headers.append('Access-Control-Allow-Headers', '*');

       console.log('calling viju method');
       console.log(headers);
       var result = this._http.get(this.myAppUrl,{headers:headers})
       .map((response: Response) => response.json());

       return result;
  }

}

##ToDoComponent.ts file code

import { Component } from '@angular/core';
import { ToDoService } from './service/to-do.service'
import { FormBuilder, FormGroup, FormControl } from '@angular/forms';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'ToDo';
  ToDolist : any[];
  ToDoForm : FormGroup;
constructor(private _fb : FormBuilder, private _service : ToDoService ){

  this.ToDoForm = this._fb.group({
    ToDoId: 0,
    Content: new FormControl(),
    Status: new FormControl(),
  });

  this.getToDoList();
}

  getToDoList(){
    // debugger;
    this._service.getToDoList()
    .subscribe(res=> this.ToDolist = res);
    debugger;
    console.log(this.ToDolist);
  }
}

Please refer to the error screenshot below.

https://i.sstatic.net/Pk4PJ.png

Answer №1

Aside from the issues highlighted in the feedback...

If you happen to be utilizing Angular version 6, it seems that your Observable imports may be incorrect. (Unless you are making use of the compatibility library?)

Below are the correct import statements for RxJS version 6:

import { Observable, throwError } from 'rxjs';
import { catchError, tap, map } from 'rxjs/operators';

It also seems like there might be a mix-up between code for the old Http and the new HttpClient.

The old Http required the usage of .json(), while the new HttpClient handles this mapping automatically.

This is how my get method looks:

getMovies(): Observable<IMovie[]> {
    return this.http.get<IMovie[]>(this.moviesUrl);
}

Alternatively, you can include console logging and error handling like so:

getMovies(): Observable<IMovie[]> {
    return this.http.get<IMovie[]>(this.moviesUrl)
      .pipe(
        tap(data => console.log(JSON.stringify(data))),
        catchError(this.handleError)
      );
}

Keep in mind that Http calls are asynchronous, hence you cannot log the results immediately after the call. They will come back as undefined. You should log within the subscribe method instead.

getToDoList(){
    // debugger;
    this._service.getToDoList()
    .subscribe(res=> {
         this.ToDolist = res;
         debugger;
         console.log(this.ToDolist);
    });
}

Answer №2

It appears that the service method is named 'GetMethod', but in the component, you are actually calling getToDoList().

Below is the revised code for the service:

GetMethod()  : Observable<any> {
    console.log("function called");
       var headers = new HttpHeaders();
       headers.append('Content-Type', 'application/json');
       headers.append('Access-Control-Allow-Origin', '*');
       headers.append('Access-Control-Allow-Methods', '*');
       headers.append('Access-Control-Allow-Headers', '*');

       return this._http.get(this.myAppUrl,{headers:headers})
       .map((response: any) => response.json());
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The subscription function in observables may result in values that are undefined

I integrated a new angular 2 library into my application called "angular2-grid". This library is located within the node_modules folder. Furthermore, I created a service as shown below: import { Injectable } from '@angular/core'; import { Htt ...

Working with button loops in react.js

Just started learning react.js and I'm trying to display a list of names as buttons. const exampleComponent: React.FC<IProps> = () => { const renderButtons= () => { for(let i=0; i<names.length; i++){ <TextButt ...

One way to incorporate type annotations into your onChange and onClick functions in TypeScript when working with React is by specifying the expected

Recently, I created a component type Properties = { label: string, autoFocus: boolean, onClick: (e: React.ClickEvent<HTMLInputElement>) => void, onChange: (e: React.ChangeEvent<HTMLInputElement>) => void } const InputField = ({ h ...

Unidentified Controller Scope in Angular and TypeScript

I am struggling with my Angular 1.5 app that uses Typescript. Here is a snippet of my code: mymodule.module.ts: angular.module('mymodule', []).component('mycomponent', new MyComponent()); mycomponent.component.ts export class MyCont ...

Angular 4 ngbtypeahead search filter

I am looking for a way to remove previous results from ngbtypeahead if the user does not select an option. Even when all characters are removed from the input text, the results should not be displayed. NgbdTypeaheadHttp.component.ts export class NgbdType ...

Improving the performance of angular-map when adding numerous markers

I am currently working on a map project in Angular 7 that involves displaying 1600 markers, but I'm encountering slow loading times. Within my .ts file, I have a function that retrieves latitude and longitude values from a JSON file: private _popula ...

ReactJS - Component with Modal functionality enabled

I have encountered an issue with a modal that I am using on both the login and home pages of my website. The modal works perfectly on the home page, but it seems to malfunction on the login page where it is displayed within its designated component. If you ...

The webpage is nowhere to be found following ng build

I've encountered an issue with my login route - it works fine on localhost, but after running ng build and accessing the login route, I get a 404 error stating "path not found." Could this be due to a mistake in setting the basehref or building proces ...

Develop a user interface that includes the ability to have unspecified properties of an unspecified data type,

interface Sample { value?: string [prop: string]: any } const sampleObject: Sample = { title: 'John' } const data = sampleObject.title By including "any" in the interface, it eliminates the automatically assumed "string" type for the p ...

Getting Angular HttpErrorResponse 403 displayed in the Visual Studio Code console

I'm currently working on a project using Angular 17.3.8 in conjunction with a non-standalone setup, and I've run into an issue that's popping up in my VSCode console that I can't seem to figure out. I've set up a login system that ...

Extending momentjs functionality with a custom method in Typescript

I am attempting to extend the momentjs prototype with a new function. In JavaScript, I achieved this with the following code: Object.getPrototypeOf(moment()).isWeekend = function() { return this.isoWeekday() >= 6; }; How can I accomplish this in T ...

The PrimeNG table fails to reset

When the reset method is applied to a PrimeNG table, it resets the icon, but it doesn't reset the data. HTML <button (click)="onReset(dt)">Reset Table</button> TS onReset = (table) => { table.reset(); } ...

In Angular, set the default value of the first item in the list to be highlighted when the page loads

In my project, there are two key components: 1)contact and 2)display. The contact component is responsible for displaying a list of contacts as shown in the image below: https://i.sstatic.net/SnXFZ.png Next to the contact component, I have placed anothe ...

What is the best way for Jasmine to utilize the FormGroup super constructor within the ngOnInit lifecycle hook?

I have created a custom form class that extends FormGroup and has the following constructor: public constructor(/* parameters */) { function myValidator(): ValidatorFn { //return validator function } super({ /* form controls */}, [myVal ...

Storage Options for Keeping Data Locally: Local Storage and Session

Here is the HTML code snippet I'm working with: <h2>Welcome User!!!</h2> <form class="container" action="/product"> <div> <label for="mail"><b>Email ID: [(ngModel)]</b> ...

Having trouble sending an HTTP request to my .Net Core 2.1 web project

In my current project, I am working with Angular 6 and .Net Core 2.1. The Angular 6 code is in one project, while the .Net Core 2.1 controller methods for login authentication are in another project. I have noticed that both projects are using different lo ...

Getting an error with the select query when using the where clause in a Node.js and Express API

I am encountering an error with my code when using a select query with a where clause. I would appreciate it if someone could help me solve this issue promptly. exports.findById = (req, res) => { const id = req.params.id; con.query('SELECT * FRO ...

Creating a custom interface in TypeScript allows you to define and enforce specific

Looking for guidance on how to properly declare an array of objects using a custom interface in TypeScript. Below is the interface I am working with: export interface Member { name: string, isLoggedIn: boolean, loginTime: Date } I attempted to decl ...

A property in TypeScript with a type that depends on the value of an object

How can we troubleshoot the error not displaying in Typescript and resolve it effectively? Explore Typescript sandbox. enum Animal { BIRD = 'bird', DOG = 'dog', } interface Smth<T extends Animal = Animal> { id: number; a ...

Convert a string into a component

I need to generate a routing file in my Angular Project where all path and component names are stored in a database. The components will be selected based on the user's login rights. Currently, I am looking to create a route array in the routing mod ...