Angular4 TypeScript JsonReaderException

时间:2018-05-07 12:33:36

标签: c# .net angular typescript asp.net-core

我有一个包含1条或多条记录的表格,显示给用户。用户选择一个或多个复选框并提交,表单提交时数据在数据库中更新。那一刻我来自代码调用location.relaod();为了重新加载页面并显示正确的数据。

以下是来自后端web api的代码:

[HttpGet]
public async Task<object> Get()
{
    var entries = await _entryRepository.GetEntriesByUserIdAsync(await GetUserId());

    var result = _mapper.Map<IEnumerable<Entries>, IEnumerable<EntryReponse>>(entries);

    return Ok(result);
}

以下是调用web api的服务代码:

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
import { AuthService } from "./auth.service";
import { Entry } from "../models/entry";
import { Observable } from 'rxjs/Rx';

@Injectable()
export class EntryService
{
    private readonly API_URL = 'http://localhost:52841/api/entry/';
    constructor(private http: Http,
        private authService: AuthService) { }


    createEntry(id) {
        let headers = new Headers();
        headers.append('Authorization', "Bearer " + this.authService.token);

        let options = new RequestOptions({ headers: headers });

        return this.http.post(this.API_URL + id, null,options);
    }

    get() {
        let headers = new Headers();
        headers.append('Authorization', "Bearer " + this.authService.token);

        let options = new RequestOptions({ headers: headers });
        return this.http.get(this.API_URL,  options).map(res => res.json());
    }

    update(entry: Entry){

        let headers = new Headers();
        headers.append('Authorization', "Bearer " + this.authService.token);

        let options = new RequestOptions({ headers: headers });
        return this.http.put(this.API_URL, entry, options);
    }

以下是组件代码:

import { Component, OnInit } from '@angular/core';
import { EntryService } from "../../services/entry.service";
import { MasterCodeService } from "../../services/masterCode.service";
import { SubCodeService } from "../../services/subcode.service";
import { Entry } from "../../models/entry";
import { MasterCode } from "../../models/masterCodes";



@Component({
    selector: 'entry-list',
    templateUrl: './entry-list.component.html'
})
export class EntryListComponent implements OnInit {



    private readonly PAGE_SIZE = 100;


    query: any = {
        pageSize: this.PAGE_SIZE
    };
    masterCodes: any = [];
    subCodes: any = [];
    masterCode: MasterCode = new MasterCode();
    entries: Entry[];
    entry: Entry ={
        id: [],
        masterCodeId: 0,
        subCodeId: 0,
        accepted: 0,
        rejected:0
};


columns = [
        { title: "#" },
        { title: "PO" },
        { title: "SKU" },
        { title: "Status" }
    ];
    constructor(private entryService: EntryService,
        private masterCodeService: MasterCodeService,
        private subCodeService: SubCodeService) {

    }

    load() {
        this.masterCodeService.getMasterCodes(this.query).subscribe(res => {
            this.masterCodes = res;
        });
        this.entryService.get().subscribe(res => {
            this.entries = res;

        });

    }

    ngOnInit() {
        this.load();


    }

    onChange(event) {
        var selectedMasterCode = this.masterCodes.items.find(x => x.id == event.target.value);
        this.entry.masterCodeId = selectedMasterCode.id;
        this.subCodeService
            .getSubCodes()
            .subscribe(res => this.subCodes = res.filter(x=>x.masterCode.id == selectedMasterCode.id));
    }

    submit(event) {

        if (event.target["noError"]) {

                this.entry.accepted = 0;
                this.entry.rejected = 0;
        }
        if (event.target["accepted"] && event.target["accepted"].checked === true ) {
            this.entry.accepted = 1;
            this.entry.rejected = 0;


        }
        if (event.target["rejected"] && event.target["rejected"].checked === true ) {
            this.entry.accepted = 0;
            this.entry.rejected = 1;
        }


        this.entryService.update(this.entry).subscribe(x => {
            location.reload();
            this.load();
        });
    }

    selectSubCode(event) {
        this.entry.subCodeId = event.target.value;
    }


    onEntryToggle(entryId, $event) {
        if ($event.target.checked)
            this.entry.id.push(entryId);
        else {
            var index = this.entry.id.indexOf(entryId);
            this.entry.id.splice(index, 1);
        }

    }



}

提交后,我收到下一个错误:

  
    

处理请求时发生未处理的异常。 JsonReaderException:解析时遇到意外的字符     价值:{。路径'errorMessage',第1行,第17位。     Newtonsoft.Json.JsonTextReader.ReadStringValue(ReadType readType)

  
     

堆栈查询Cookie标头JsonReaderException:意外的字符   在解析值时遇到:{。路径'errorMessage',第1行,   位置17. Newtonsoft.Json.JsonTextReader.ReadStringValue(ReadType   readType)Newtonsoft.Json.JsonTextReader.ReadAsString()   Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader   读者,JsonContract合同,bool hasConverter)   Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(对象   newObject,JsonReader reader,JsonObjectContract契约,   JsonProperty成员,字符串id)   Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader   reader,Type objectType,JsonContract契约,JsonProperty成员,   JsonContainerContract containerContract,JsonProperty containerMember,   object existingValue)   Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader   reader,Type objectType,JsonContract契约,JsonProperty成员,   JsonContainerContract containerContract,JsonProperty containerMember,   object existingValue)   Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader   reader,Type objectType,bool checkAdditionalContent)   Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader阅读器,   输入objectType)Newtonsoft.Json.JsonConvert.DeserializeObject(string   value,Type type,JsonSerializerSettings设置)   Newtonsoft.Json.JsonConvert.DeserializeObject(字符串值,   JsonSerializerSettings设置)   Microsoft.AspNetCore.NodeServices.HostingModels.HttpNodeInstance + d__7.MoveNext()   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务   任务)System.Runtime.CompilerServices.TaskAwaiter.GetResult()   Microsoft.AspNetCore.NodeServices.HostingModels.OutOfProcessNodeInstance + d__13.MoveNext()   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务   任务)System.Runtime.CompilerServices.TaskAwaiter.GetResult()   Microsoft.AspNetCore.NodeServices.NodeServicesImpl + d__10.MoveNext()   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务   任务)System.Runtime.CompilerServices.TaskAwaiter.GetResult()   Microsoft.AspNetCore.NodeServices.NodeServicesImpl + d__10.MoveNext()   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务   任务)System.Runtime.CompilerServices.TaskAwaiter.GetResult()   Microsoft.AspNetCore.SpaServices.Prerendering.PrerenderTagHelper + d__29.MoveNext()   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务   任务)   Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner + d__0.MoveNext()   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务   任务)   AspNetCore._Views_Home_Index_cshtml + d__12.MoveNext()in   Index.cshtml

请你告诉我如何解决这个问题? 附:同样的错误如果我不提交表单只需要F5重新加载页面,我也会得到。

更新 第一次调用时是JSON: enter image description here From Network panel

重装后: enter image description here

Header 1st call: enter image description here

重装后的标题: enter image description here

我对一些重新加载的URL路径的理解是有效的,而且其中一些不起作用。回顾一下,有些路由可以手动输入到浏览器中调用,其中一些只能从链接调用,为什么?如果所有链接,所有组件,所有服务都以相同的方式创建,我怎么能弄清楚哪里出错? 亲切的问候, 达尼耶尔

1 个答案:

答案 0 :(得分:0)

我修复了代码

load() {
    this.entryService.get().subscribe(res => {

        this.entries = res;
},err=>console.log(err));
this.masterCodeService.getMasterCodes(this.query).subscribe(res => {
    this.masterCodes = res;
});



}

这对我来说是解决方案并且是如何帮助我以及为什么我应该添加err =&gt; console.log(错误)不知道。如果有人能够澄清这一点,我将不胜感激。

**我错了,解决方案在app.shared.ts中 在路由配置中,我添加了canActive

{path:'entries',component:EntryListComponent,canActivate:[AuthGuard]},

由于API已获得授权,因此这是强制性的。**