【问题标题】:Angular 2 TypeError: Object doesn't support property or method 'json'Angular 2 TypeError:对象不支持属性或方法'json'
【发布时间】:2017-12-08 04:33:30
【问题描述】:

我正在使用 Angular 2 前端和 MVC 后端构建一个引用 SSMS 数据库的基本 CRUD 应用程序。当我在任何浏览器上运行我的 HTTPGet 时,我遇到了错误:

TypeError:对象不支持属性或方法'json'

我为服务调用设置了一个调试点,但它没有到达那里,所以我假设问题出在某处的组件中..

我已经用谷歌搜索了大约一天半,发现很多人在“json”的位置有其他东西,但我找不到其他人有这个问题。您将在下面找到我的 Get。如果您需要任何其他 sn-ps,请告诉我。

这是我的 Get 组件:

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';

@Component({

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: ['']
    });

    this.getCorrectionCodes();

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

还有,这是我的服务:

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';
@Injectable()
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)));

    }

这是我的 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';

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

export class AppModule { }

这是我的控制器:

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();
        }

        [HttpGet]
        public HttpResponseMessage Get()
        {
            var corrCodes = context.GetAllCorrectionCodes(ProgramAreaName).AsEnumerable();
                return ToJson(corrCodes);
        }

我的 ToJson 方法:

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

和我的上下文数据库存储库:

 public IEnumerable<CorrectionCode> GetAllCorrectionCodes(string pgm_area_name)
        {
            using (con)
            {
                 con.Open();
                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 在屏幕显示“TypeError:error.json is not a function”时从 Google Developer Tools 编译 Tile 错误:

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)

这是 IE11 中错误读数的屏幕截图,屏幕显示“TypeError: Object doesn't support property or method 'json'”:

【问题讨论】:

  • 您不使用 HttpClient 而不是 Http 的任何具体原因?它将消除在.map((response: Response) =&gt; &lt;any&gt;response.json()) 上调用.json 的需要;参考:angular.io/guide/http
  • @joshvito 不确定如何获取 HTTPClient 而不是 Http。我是 Angular 2 引用风格的新手。你能解释一下我会在 package.json 和 systemjs.config.js 中放什么
  • map((response: Response) =&gt; response.json() as any)可以这样试试吗?
  • @tCoe,我喜欢你的角度文档,它引导你完成设置新的 HttpClient。按照本指南angular.io/guide/http
  • 上面发布的角度代码对我来说看起来不错。我没有看到任何明显的错误。您是否使用带有 ts-lint 的 IDE,可能存在不那么明显的类型错误?我为你投票赞成这个问题。也许下一个调试步骤是尝试在 jsfiddle 等上添加指向可重现错误的链接。

标签: json asp.net-mvc angular typescript


【解决方案1】:

我强烈建议您使用 Http Client 代替 Http,因为第一个已弃用。使用起来很简单:

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

@Injectable()
export class AccountService {

  constructor(private http: HttpClient) {
   ...
  }

当然,您也应该在 app.module 中以与 Http 相同的形式声明 HttpClient。

【讨论】:

  • 我没有使用具有 HttpClient 的 Angular 版本,如帖子下方的 cmets 中所述。
【解决方案2】:

事实证明@joshvito 是在正确的轨道上,Angular 没问题,只是不完全正确。问题是,在我遵循的教程中,它建议我将 RouteConfig.ts 编辑为:

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

但是该示例使用的是 Web Api 而不是 ASP.net,而且因为我对 Angular 还很陌生,所以我不知道我应该一直在编辑 WebApiConfig.cs,它期待一个我没有的操作名称传入。所以当我将组件中的 get 方法更改为:

getCorrectionCodes(): void {
        this.indLoading = true;
        this._corrCodeService.get(Global.BASE_CORRECTION_CODE_ENDPOINT+"get")
            .subscribe(corrCodes => {
                this.corrCodes = corrCodes; this.indLoading = false;
            }, error => this.msg = <any>error);
    }

一切都开始正常工作了。

【讨论】:

    猜你喜欢
    • 2015-07-02
    • 1970-01-01
    • 2018-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-13
    • 2013-12-28
    • 2019-03-31
    相关资源
    最近更新 更多