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