我正在使用Angular 2前端和MVC后端构建一个引用SSMS数据库的基本CRUD应用程序。当我在任何浏览器上运行HTTPGet时,我遇到了错误:
TypeError:对象不支持属性或方法' json'
我为服务调用设置了一个调试点,但它没有到达那里,所以我假设问题出现在组件的某个地方..
我用Google搜索了大约一天半的时间,发现很多人在“json”的位置上还有其他东西,但我找不到其他任何人正是这个问题。下面你会发现我的Get。如果您需要任何其他代码段,请告诉我们。
这是我的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;
}
和我的Contextual DB Repository:
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;
}
}
编辑#1在屏幕显示&#34; TypeError:error.json不是函数&#34;来自Google Developer Tools时编译平铺错误&#34;:
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中错误读数的屏幕截图,屏幕显示&#34; TypeError:对象不支持属性或方法&#39; json&#39;&#34;:
答案 0 :(得分:2)
我强烈建议您使用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。
答案 1 :(得分:0)
事实证明@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);
}
一切都开始发挥作用了。