-1

I am getting really weird behavior trying to call the Controller in .net 5 MVC project from the angular 12. I am getting 200 status code and even get the data that I suppose to get but at the same response I am getting the error message **"Unexpected token e in JSON at position 0"**.enter image description here I am able to use the postman and call the controller with no problem so that makes me think the problem is with the Angular.

Here is how my angular side looks like:

data.service.ts:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Token } from './models/token';

import { Observable } from 'rxjs';

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

  constructor(private http: HttpClient) { }

  getEco(input:string):Observable<string>{
    return this.http.get<string>(`home/${input}`,{ headers: this.headers});
  }

  getToken(): Observable<Token> {
    return this.http.post<Token>("token/generate", {headers: this.headers })
  }
  private headers: HttpHeaders = new HttpHeaders({ 'Content-Type': 'application/json' });

component:

import { Component, OnInit } from '@angular/core';
import { DataService } from './data-service.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'ClientApp';
  constructor(private dataService: DataService){}
  ngOnInit(): void {

    this.dataService.getEco("ahanahui").subscribe((res) =>{
      console.log(res);
    });

    this.dataService.getToken().subscribe(res => console.log(res));

  }
}
  • 1
    Does this answer your question? [Angular Unexpected token c in JSON at position 0 at JSON.parse when expecting a string](https://stackoverflow.com/questions/62046090/angular-unexpected-token-c-in-json-at-position-0-at-json-parse-when-expecting-a) – R. Richards Jan 16 '22 at 19:14
  • That does solve the problem only for the string call. When you expect the response to be a string. But it looks like a hack or kind of work around. I think I am missing something on the set up level. Thank you anyway – Stanislav Mozolevskiy Jan 16 '22 at 23:37
  • I was missing the NewtonsoftJson that would serialize response for me https://www.newtonsoft.com/json – Stanislav Mozolevskiy Jan 17 '22 at 00:41

1 Answers1

0

I was missing the NewtonsoftJson that would serialize response for me newtonsoft.com/json

   public static class ConfigurationExtensions
    {
        public static IServiceCollection ConfigureMVC(this IServiceCollection services)
        {
            services.AddNewtonsoftJson(options =>
                {
                    options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                    options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                });
            return services;
        }
    }