Home Angular 2 TypeError: Object doesn't support property or method 'json'
Reply: 2

Angular 2 TypeError: Object doesn't support property or method 'json'

tCoe Published in 2017-12-07 15:48:51Z

I am building a basic CRUD application that references a SSMS database, using an Angular 2 front end and a MVC back end. I am running into the error when i run my HTTPGet on any browser:

TypeError: Object doesn't support property or method 'json'

I have a debug point set for the service call but it doesn't get there, so I am assuming the issue is in the component somewhere..

I have googled for about a day and a half, and have found a lot of people that have other things in the place of the 'json', but I cannot find anyone else with this issue exactly. Below you will find the could for my Get. If there is any other snippets you need please let me know.

Here is my Get component:

import { Component, OnInit, ViewChild } from '@angular/core';
import { CorrectionCodeService } from '../Service/correctioncode.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal';
import { ICorrectionCode } from '../Models/ICorrectionCode';
import { DBOperation } from '../Shared/enum';
import { Observable } from 'rxjs/Rx';
import { Global } from '../Shared/global';


templateUrl: 'app/Components/correctioncode.component.html'


`enter code here`export class CorrectionCodeComponent implements OnInit {

@ViewChild('modal') modal: ModalComponent;
corrCodes: ICorrectionCode[];
corrCode: ICorrectionCode;
msg: string;
indLoading: boolean = false;
form: FormGroup;
dbops: DBOperation;
modalTitle: string;
modalBtnTitle: string;

constructor(private fb: FormBuilder,private _corrCodeService: CorrectionCodeService) { }

ngOnInit() {
    this.form = this.fb.group({
        id: [''],
        pgm_code_name: [''],
        rec_act_code: [''],
        rgln_Year: [''],
        rgln_type_name: [''],
        rgln_one_code: [''],
        rgln_two_code: [''],
        rgln_three_code: [''],
        rgln_title_text: [''],
        rgln_desc_text: [''],
        sevrty_code: [''],
        valdtn_value: [''],
        last_updt_dt: [''],
        last_updt_logn_id: [''],
        creat_dt: [''],
        creat_logn_id: [''],
        del_dt: [''],
        del_logn_id: [''],
        prev_rec_id: ['']


 getCorrectionCodes(): void {
    this.indLoading = true;
        .subscribe(corrCodes => {
            this.corrCodes = corrCodes; this.indLoading = false;
        }, error => this.msg = <any>error);

And, here is my service:

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
export class CorrectionCodeService {
    constructor(private _http: Http) { }

    get(url: string): Observable<any> {
        let headers = new Headers({ 'accept': 'applicationCache/json' });
        let options = new RequestOptions({ headers: headers });
        return this._http.get(url,options)
            .map((response: Response) => <any>response.json())
            // .do(data => console.log("All: " + JSON.stringify(data)));


here is my app.module.ts:

import { NgModule } from '@angular/core';
import { APP_BASE_HREF } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HttpModule } from '@angular/http';
import { routing } from './app.routing';
import { HomeComponent } from './Components/home.component';
import { CorrectionCodeComponent } from './Components/correctioncode.component';
import { Ng2Bs3ModalModule } from 'ng2-bs3-modal/ng2-bs3-modal';
import { CorrectionCodeService } from './Service/correctioncode.service';
import { UploadFileComponent } from './Components/uploadFile.component';
import { UploadFileService } from './Service/uploadFile.service';

    imports: [BrowserModule, ReactiveFormsModule, HttpModule, routing, Ng2Bs3ModalModule],
    declarations: [AppComponent, CorrectionCodeComponent, HomeComponent,  UploadFileComponent],
    providers: [{ provide: APP_BASE_HREF, useValue: '/' }, CorrectionCodeService, UploadFileService],
    bootstrap: [AppComponent]

export class AppModule { }

Here is my controller:

using CorrectionCodeEditor.Models;
using CorrectionCodeEditor.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;

namespace CorrectionCodeEditor.Controllers
    public class CorrectionCodeController : BaseAPIController
        string ProgramAreaName = "FAS";
        private CorrectionCodeRepository context;
        public CorrectionCodeController()

            context = new CorrectionCodeRepository();

        public HttpResponseMessage Get()
            var corrCodes = context.GetAllCorrectionCodes(ProgramAreaName).AsEnumerable();
                return ToJson(corrCodes);

my ToJson method:

protected HttpResponseMessage ToJson(dynamic obj)
            var response = Request.CreateResponse(HttpStatusCode.OK);
            response.Content = new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json");
            return response;

and my Contextual DB Repository:

 public IEnumerable<CorrectionCode> GetAllCorrectionCodes(string pgm_area_name)
            using (con)
                var dP = new DynamicParameters();
                dP.Add("@ProgramAreaName", pgm_area_name);
                IEnumerable<CorrectionCode> corrCodeList = con.Query<CorrectionCode>("[mobile].[p_get_correction_codes_by_params]", dP, commandType: CommandType.StoredProcedure);
                return corrCodeList;

EDIT#1 Compile Tile Error from Google Developer Tools while the screen displays "TypeError: error.json is not a function":

SyntaxError: Unexpected token < in JSON at position 0
    at JSON.parse (<anonymous>)
    at Response.Body.json (body.ts:36)
    at MapSubscriber.eval [as project] (correctioncode.service.ts:12)
    at MapSubscriber._next (map.ts:75)
    at MapSubscriber.Subscriber.next (Subscriber.ts:95)
    at XMLHttpRequest.onLoad (xhr_backend.ts:104)
    at ZoneDelegate.invokeTask (zone.js:265)
    at Object.onInvokeTask (ng_zone.ts:254)
    at ZoneDelegate.invokeTask (zone.js:264)
    at Zone.runTask (zone.js:154)

here is a screenshot of the error readout in IE11 while the screen is saying "TypeError: Object doesn't support property or method 'json'":

freedeveloper Reply to 2017-12-07 20:17:30Z

I strongly suggest you to use the Http Client instead Http, because the first is deprecated. to use it simple:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

export class AccountService {

  constructor(private http: HttpClient) {

Of Course you should declare HttpClient also in your app.module in the same form that Http.

tCoe Reply to 2017-12-07 20:33:30Z

Turns out @joshvito was on the right track with the Angular being ok, just not completely correct. The problem is that in the tutorial i was following, it suggested that i edit the RouteConfig.ts to:

 public static void RegisterRoutes(RouteCollection routes)
                            name: "Default",
                            url: "{*anything}",
                            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }

But the example was using Web Api not ASP.net, and because I am so new to Angular, I didn't know that I should have been editing the WebApiConfig.cs, which was expecting an action name that I was not passing in. so when i changed my get method in my component to this:

getCorrectionCodes(): void {
        this.indLoading = true;
            .subscribe(corrCodes => {
                this.corrCodes = corrCodes; this.indLoading = false;
            }, error => this.msg = <any>error);

Everything started to work as it should.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.308809 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO